Skip to content

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

✨ feat(agent-documents): collapse folders into a progressive index row (#16578)

Arvin Xu54a0f3cb2230
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
index 4a075544211..4069a3ee2ae 100644
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ b/apps/server/src/routers/lambda/agentDocument.ts
@@ -502,26 +502,33 @@ export const agentDocumentRouter = router({
// Reveal the auto-created `.tool-results` archive. Off by default so
// user-facing lists stay clean; the agent document-listing tool opts in.
includeArchivedToolResults: z.boolean().optional().default(false),
+ // Restrict the listing to the direct children of this folder so the model
+ // can expand a folder collapsed in the progressive index (LOBE-11072).
+ parentId: z.string().optional(),
scope: z.enum(['agent', 'currentTopic']).optional().default('agent'),
sourceType: z.enum(['all', 'file', 'web']).optional().default('all'),
topicId: z.string().optional(),
}),
)
.query(async ({ ctx, input }) => {
- const { includeArchivedToolResults } = input;
+ const { includeArchivedToolResults, parentId } = input;
if (input.scope === 'currentTopic') {
if (!input.topicId) throw new Error('topicId is required to list current topic documents');
- return ctx.agentDocumentService.listDocumentsForTopic(
+ const docs = await ctx.agentDocumentService.listDocumentsForTopic(
input.agentId,
input.topicId,
input.sourceType,
{ includeArchivedToolResults },
);
+ // 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;
}
return ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {
includeArchivedToolResults,
+ parentId,
});
}),
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.ts
index 525a610a830..d2f33ad81e6 100644
--- a/apps/server/src/services/agentDocuments/index.test.ts
+++ b/apps/server/src/services/agentDocuments/index.test.ts
@@ -305,7 +305,10 @@ describe('AgentDocumentsService', () => {
const service = new AgentDocumentsService(db, userId);
const result = await service.listDocuments('agent-1');
- expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1');
+ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', {
+ parentId: undefined,
+ sourceType: undefined,
+ });
expect(mockModel.findByAgent).not.toHaveBeenCalled();
expect(result).toEqual([
{
@@ -331,10 +334,25 @@ describe('AgentDocumentsService', () => {
const service = new AgentDocumentsService(db, userId);
await service.listDocuments('agent-1', 'web');
- expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', { sourceType: 'web' });
+ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', {
+ parentId: undefined,
+ sourceType: 'web',
+ });
expect(mockModel.findByAgent).not.toHaveBeenCalled();
});
+ it('should pass the parentId folder filter to the model', async () => {
+ mockModel.listByAgent.mockResolvedValue([]);
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.listDocuments('agent-1', undefined, { parentId: 'folder-1' });
+
+ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', {
+ parentId: 'folder-1',
+ sourceType: undefined,
+ });
+ });
+
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.ts
index 334b6d5d3fc..52d105c4d38 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -118,10 +118,13 @@ const toAgentDocumentContextPayload = (
content: doc.content,
contentCharCount: doc.contentCharCount,
description: doc.description,
+ documentId: doc.documentId,
filename: doc.filename,
+ fileType: doc.fileType,
id: doc.id,
isFolder: doc.isFolder,
loadRules: doc.loadRules,
+ parentId: doc.parentId,
policy: doc.policy,
policyLoad: doc.policyLoad,
policyLoadFormat: doc.policyLoadFormat,
@@ -629,11 +632,12 @@ export class AgentDocumentsService {
async listDocuments(
agentId: string,
sourceType?: AgentDocumentListSourceType,
- options?: { includeArchivedToolResults?: boolean },
+ options?: { includeArchivedToolResults?: boolean; parentId?: string },
) {
- const docs = sourceType
- ? await this.agentDocumentModel.listByAgent(agentId, { sourceType })
- : await this.agentDocumentModel.listByAgent(agentId);
+ const docs = await this.agentDocumentModel.listByAgent(agentId, {
+ parentId: options?.parentId,
+ sourceType,
+ });
return options?.includeArchivedToolResults ? docs : excludeArchivedToolResults(docs);
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
index 97bd5e0b533..c49b3424a4d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
@@ -183,11 +183,12 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
() => service.createForTopic(agentId, title, content, topicId, { hintIsSkill }),
),
),
- listDocuments: async ({ agentId, sourceType }) => {
+ listDocuments: async ({ agentId, parentId, sourceType }) => {
// Agents discover archived tool results via this path (see
// `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.
const docs = await service.listDocuments(agentId, sourceType, {
includeArchivedToolResults: true,
+ parentId,
});
return docs.map((d) => ({
documentId: d.documentId,
@@ -196,11 +197,14 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
title: d.title,
}));
},
- listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
+ listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {
const docs = await service.listDocumentsForTopic(agentId, topicId, sourceType, {
includeArchivedToolResults: true,
});
- return docs.map((d) => ({
+ // 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,
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index 78f59395f89..88c49ba3858 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -260,6 +260,7 @@ export class AgentDocumentsExecutionRuntime {
const scope = args.scope ?? 'agent';
const sourceType = args.sourceType ?? 'all';
+ const parentId = args.parentId;
const topicId = this.resolveTopicId(context);
if (scope === 'currentTopic' && !topicId) {
return {
@@ -270,8 +271,14 @@ export class AgentDocumentsExecutionRuntime {
const docs =
scope === 'currentTopic'
- ? await this.service.listTopicDocuments({ agentId, scope, sourceType, topicId: topicId! })
- : await this.service.listDocuments({ agentId, scope, sourceType });
+ ? await this.service.listTopicDocuments({
+ agentId,
+ parentId,
+ scope,
+ sourceType,
+ topicId: topicId!,
+ })
+ : await this.service.listDocuments({ agentId, parentId, scope, sourceType });
const list = await Promise.all(
docs.map(async (d) => {
const url = await this.buildDocumentUrl(agentId, d.documentId);
diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.ts
index f8c6688996d..fe51083d51e 100644
--- a/packages/builtin-tool-agent-documents/src/manifest.ts
+++ b/packages/builtin-tool-agent-documents/src/manifest.ts
@@ -194,10 +194,15 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- 'List agent documents. Use this to discover documents that are not auto-injected (e.g. web-crawled pages) or to resolve a title to a document ID.',
+ 'List agent documents. 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.',
name: AgentDocumentsApiName.listDocuments,
parameters: {
properties: {
+ 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.',
+ type: 'string',
+ },
scope: {
default: 'agent',
description:
diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.ts
index d87fd72558b..210122783f6 100644
--- a/packages/builtin-tool-agent-documents/src/systemRole.ts
+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts
@@ -25,7 +25,7 @@ export const systemPrompt = `You have access to an Agent Documents tool for crea
- 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. Use this to resolve a title to a document ID before reading.
+- **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.
- **readDocument**: retrieve current content by document ID. 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.
- **replaceDocumentContent**: overwrite the full content of an existing document only when replacing most or all content.
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index b1fba0ee1f7..d8297846a29 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -154,6 +154,12 @@ 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.
+ */
+ parentId?: string;
scope?: 'agent' | 'currentTopic';
sourceType?: 'all' | 'file' | 'web';
}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
index 724b49a8fa0..8f598fee230 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
@@ -31,9 +31,22 @@ export interface AgentContextDocument {
contentCharCount?: number;
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.
+ */
+ folderTitle?: string;
id?: string;
loadPosition?: AgentDocumentInjectionPosition;
loadRules?: AgentDocumentLoadRules;
+ /**
+ * Parent folder's `documentId` (the `documents.id` of the `custom/folder`
+ * row). Doubles as the grouping key for folder folding and the value the
+ * model passes to `listDocuments(parentId=…)` to expand a folded folder.
+ */
+ parentId?: string | null;
policyId?: string | null;
policyLoad?: AgentDocumentPolicyLoad;
policyLoadFormat?: AgentDocumentLoadFormat;
@@ -201,6 +214,104 @@ function buildIndexTable(
return [headerLine, ...dataLines].join('\n');
}
+const FOLDER_ICON = 'πŸ“';
+
+interface FolderGroup {
+ docs: AgentContextDocument[];
+ parentId: string;
+ title: string;
+}
+
+/** Newest `updatedAt` among a group of docs as epoch ms (0 when none is set). */
+function newestTime(docs: AgentContextDocument[]): number {
+ return docs.reduce((max, d) => {
+ const t = d.updatedAt ? new Date(d.updatedAt).getTime() : 0;
+ return Number.isNaN(t) ? max : Math.max(max, t);
+ }, 0);
+}
+
+/**
+ * Split progressive docs into folders worth collapsing and the loose docs that
+ * stay flat. A folder is collapsed only when it holds β‰₯2 docs carrying a
+ * resolved `folderTitle` β€” a lone doc-in-folder reads better as its own row so
+ * its id stays directly `readDocument`-able. Docs with no known folder (root
+ * docs, or docs whose folder was filtered out upstream) always stay flat.
+ */
+function partitionFolders(docs: AgentContextDocument[]): {
+ flat: AgentContextDocument[];
+ folders: FolderGroup[];
+} {
+ const byParent = new Map<string, AgentContextDocument[]>();
+ const flat: AgentContextDocument[] = [];
+ for (const doc of docs) {
+ if (doc.parentId && doc.folderTitle) {
+ const arr = byParent.get(doc.parentId);
+ if (arr) arr.push(doc);
+ else byParent.set(doc.parentId, [doc]);
+ } else {
+ flat.push(doc);
+ }
+ }
+
+ 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);
+ }
+ return { flat, folders };
+}
+
+/**
+ * "18 docs, 4.3k–20k" β€” count plus a size range when the folder's docs differ
+ * meaningfully in size; just the count when they're uniform or all empty.
+ */
+function formatFolderSummary(docs: AgentContextDocument[]): string {
+ const count = `${docs.length} docs`;
+ const lens = docs.map((d) => d.contentCharCount ?? d.content?.length ?? 0);
+ const max = Math.max(...lens);
+ if (max === 0) return count;
+ const min = Math.min(...lens.filter((l) => l > 0));
+ const minStr = formatSize({ contentCharCount: min });
+ const maxStr = formatSize({ contentCharCount: max });
+ return minStr === maxStr ? `${count}, ${maxStr}` : `${count}, ${minStr}–${maxStr}`;
+}
+
+/**
+ * Render collapsed folders as a fixed-width table, newest folder first:
+ *
+ * πŸ“ dailyBrief 2af6…394efa 18 docs, 4.3k–20k 1mo ago
+ * πŸ“ 周ζŠ₯ 6b1c…07d21 9 docs 1mo ago
+ *
+ * The ID column is the folder's `documentId` β€” the value the model passes to
+ * `listDocuments(parentId=…)` to expand the folder on demand.
+ */
+function buildFolderTable(folders: FolderGroup[], now: Date): string {
+ const rows = folders
+ .map((f) => ({
+ id: f.parentId,
+ summary: formatFolderSummary(f.docs),
+ time: newestTime(f.docs),
+ title: `${FOLDER_ICON} ${truncate(f.title, TITLE_MAX_WIDTH)}`,
+ }))
+ .sort((a, b) => b.time - a.time);
+
+ const titleWidth = Math.max(...rows.map((r) => r.title.length));
+ const idWidth = Math.max(...rows.map((r) => r.id.length));
+ const summaryWidth = Math.max(...rows.map((r) => r.summary.length));
+
+ const sep = ' ';
+ return rows
+ .map((row) =>
+ [
+ row.title.padEnd(titleWidth),
+ row.id.padEnd(idWidth),
+ row.summary.padEnd(summaryWidth),
+ row.time ? formatRelative(new Date(row.time), now) : 'β€”',
+ ].join(sep),
+ )
+ .join('\n');
+}
+
/**
* Sort documents by recency (most-recently-updated first); rows missing
* `updatedAt` sink to the end and keep stable input order between themselves.
@@ -244,9 +355,14 @@ export function combineDocuments(
}
if (progressiveDocs.length > 0) {
- const userDocs = sortByRecency(progressiveDocs.filter((d) => d.sourceType !== 'web'));
+ const userDocs = progressiveDocs.filter((d) => d.sourceType !== 'web');
const hiddenWebCount = progressiveDocs.length - userDocs.length;
+ // Loose docs render as flat rows; docs sharing a folder (β‰₯2) collapse into
+ // one summary row so archive-heavy agents don't spend tokens on every entry.
+ const { flat, folders } = partitionFolders(userDocs);
+ const now = context.currentTime ?? new Date();
+
const headerLines: string[] = [
`${userDocs.length} user-created doc${userDocs.length === 1 ? '' : 's'}. Use readDocument(id) for full content.`,
];
@@ -255,8 +371,16 @@ export function combineDocuments(
`${hiddenWebCount} web-crawled doc${hiddenWebCount === 1 ? '' : 's'} hidden β€” call listDocuments(sourceType='web') to see them.`,
);
}
+ if (folders.length > 0) {
+ headerLines.push(
+ `${folders.length} folder${folders.length === 1 ? '' : 's'} collapsed (${FOLDER_ICON}) β€” call listDocuments(parentId=<id>) to list a folder's docs.`,
+ );
+ }
- const tableBlock = userDocs.length > 0 ? `\n\n${buildIndexTable(userDocs, context)}` : '';
+ const bodyBlocks: string[] = [];
+ if (flat.length > 0) bodyBlocks.push(buildIndexTable(sortByRecency(flat), context));
+ if (folders.length > 0) bodyBlocks.push(buildFolderTable(folders, now));
+ const tableBlock = bodyBlocks.length > 0 ? `\n\n${bodyBlocks.join('\n\n')}` : '';
parts.push(
`<agent_documents_index>\n${headerLines.join('\n')}${tableBlock}\n</agent_documents_index>`,
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
index 29f3b97aa27..6762cbc36d9 100644
--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
@@ -306,6 +306,112 @@ describe('AgentDocumentInjector', () => {
expect(result.messages[0].content).not.toContain('Gold news');
});
+ it('should collapse same-folder docs into a summary row and keep root docs flat', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentTime: new Date('2026-04-29T00:00:00.000Z'),
+ documents: [
+ {
+ content: 'root note',
+ filename: 'root.md',
+ id: 'root-1',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ policyLoad: 'progressive',
+ sourceType: 'file',
+ title: 'Root note',
+ updatedAt: new Date('2026-04-28T00:00:00.000Z'),
+ },
+ {
+ content: 'a'.repeat(4300),
+ filename: 'brief-1.md',
+ folderTitle: 'dailyBrief',
+ id: 'daily-1',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ parentId: 'folder-daily',
+ policyLoad: 'progressive',
+ sourceType: 'file',
+ title: 'Brief 1',
+ updatedAt: new Date('2026-04-27T00:00:00.000Z'),
+ },
+ {
+ content: 'a'.repeat(20_000),
+ filename: 'brief-2.md',
+ folderTitle: 'dailyBrief',
+ id: 'daily-2',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ parentId: 'folder-daily',
+ policyLoad: 'progressive',
+ sourceType: 'file',
+ title: 'Brief 2',
+ updatedAt: new Date('2026-04-25T00:00:00.000Z'),
+ },
+ {
+ content: 'a'.repeat(12_000),
+ filename: 'brief-3.md',
+ folderTitle: 'dailyBrief',
+ id: 'daily-3',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ parentId: 'folder-daily',
+ policyLoad: 'progressive',
+ sourceType: 'file',
+ title: 'Brief 3',
+ updatedAt: new Date('2026-04-26T00:00:00.000Z'),
+ },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchInlineSnapshot(`
+ "<agent_documents_index>
+ 4 user-created docs. Use readDocument(id) for full content.
+ 1 folder collapsed (πŸ“) β€” call listDocuments(parentId=<id>) to list a folder's docs.
+
+ TITLE ID SIZE UPDATED
+ Root note root-1 9 1d ago
+
+ πŸ“ dailyBrief folder-daily 3 docs, 4.3k–20k 2d ago
+ </agent_documents_index>"
+ `);
+ // Individual folded doc ids are hidden β€” the model expands via listDocuments.
+ expect(result.messages[0].content).not.toContain('daily-1');
+ expect(result.messages[0].content).not.toContain('daily-2');
+ });
+
+ it('should keep a lone doc-in-folder flat instead of collapsing it', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentTime: new Date('2026-04-29T00:00:00.000Z'),
+ documents: [
+ {
+ content: 'solo note',
+ filename: 'solo.md',
+ folderTitle: 'Archive',
+ id: 'solo-1',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ parentId: 'folder-archive',
+ policyLoad: 'progressive',
+ sourceType: 'file',
+ title: 'Solo',
+ updatedAt: new Date('2026-04-27T00:00:00.000Z'),
+ },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ const injected = result.messages[0].content;
+ // Rendered as a normal flat row (id readable), not a πŸ“ fold.
+ expect(injected).toContain('solo-1');
+ expect(injected).not.toContain('πŸ“');
+ expect(injected).not.toContain('folder collapsed');
+ });
+
it('should render empty docs with size=empty so the LLM does not retry', async () => {
const provider = new AgentDocumentContextInjector({
currentTime: new Date('2026-04-29T00:00:00.000Z'),
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index f2281a94097..1eed5f6e108 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -951,9 +951,10 @@ export class AgentDocumentModel {
async listByAgent(
agentId: string,
- options?: { sourceType?: AgentDocumentListSourceType },
+ options?: { parentId?: string; sourceType?: AgentDocumentListSourceType },
): Promise<AgentDocumentListItem[]> {
const sourceType = options?.sourceType;
+ const parentId = options?.parentId;
const results = await this.db
.select({
description: documents.description,
@@ -976,6 +977,7 @@ export class AgentDocumentModel {
eq(agentDocuments.agentId, agentId),
isNull(agentDocuments.deletedAt),
...(sourceType && sourceType !== 'all' ? [eq(documents.sourceType, sourceType)] : []),
+ ...(parentId ? [eq(documents.parentId, parentId)] : []),
),
)
.orderBy(desc(agentDocuments.updatedAt));
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index e7ff1976516..8a10314bd72 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -123,10 +123,13 @@ export interface AgentDocumentContextPayload {
content: string;
contentCharCount?: number;
description: string | null;
+ documentId: string;
filename: string;
+ fileType: string;
id: string;
isFolder: boolean;
loadRules: DocumentLoadRules;
+ parentId: string | null;
policy: AgentDocumentPolicy | null;
policyLoad: PolicyLoad;
policyLoadFormat: DocumentLoadFormat;
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index dccea25616b..1984db16350 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -59,6 +59,7 @@ class AgentDocumentService {
listDocuments = async (params: {
agentId: string;
includeArchivedToolResults?: boolean;
+ parentId?: string;
scope?: 'agent' | 'currentTopic';
sourceType?: 'all' | 'file' | 'web';
topicId?: string;
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
index 455388fc63b..bae814a36bb 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -49,12 +49,13 @@ const runtime = new AgentDocumentsExecutionRuntime(
topicId,
trigger,
}),
- listDocuments: async ({ agentId, sourceType }) => {
+ listDocuments: async ({ agentId, parentId, sourceType }) => {
// The agent listing tool surfaces archived `.tool-results` so the model can
// discover them; user-facing lists keep the default (filtered) behavior.
const docs = await agentDocumentService.listDocuments({
agentId,
includeArchivedToolResults: true,
+ parentId,
sourceType,
});
return docs.map((d) => ({
@@ -64,10 +65,11 @@ const runtime = new AgentDocumentsExecutionRuntime(
title: d.title,
}));
},
- listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
+ listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {
const docs = await agentDocumentService.listDocuments({
agentId,
includeArchivedToolResults: true,
+ parentId,
scope: 'currentTopic',
sourceType,
topicId,
diff --git a/src/utils/__tests__/agentDocumentContextMapping.test.ts b/src/utils/__tests__/agentDocumentContextMapping.test.ts
index 6f30f3f30ca..127c946d00f 100644
--- a/src/utils/__tests__/agentDocumentContextMapping.test.ts
+++ b/src/utils/__tests__/agentDocumentContextMapping.test.ts
@@ -175,6 +175,30 @@ describe('toAgentContextDocuments', () => {
expect(result.map((d) => d.id)).toEqual(['doc']);
});
+ // LOBE-11072: children inherit their `custom/folder` parent's title so the
+ // progressive index can fold same-folder siblings under a readable name. The
+ // folder row is still dropped β€” only its title survives, on the children.
+ it('stamps folderTitle on children of a custom/folder and drops the folder row', () => {
+ const rows = [
+ buildDoc({
+ documentId: 'folder-doc',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id: 'folder-agentdoc',
+ isFolder: true,
+ title: 'dailyBrief',
+ }),
+ buildDoc({ id: 'child-1', parentId: 'folder-doc', sourceType: 'file' }),
+ buildDoc({ id: 'child-2', parentId: 'folder-doc', sourceType: 'file' }),
+ buildDoc({ id: 'root', parentId: null, sourceType: 'file' }),
+ ];
+
+ const result = toAgentContextDocuments(rows);
+
+ expect(result.map((d) => d.id)).toEqual(['child-1', 'child-2', 'root']);
+ expect(result.map((d) => d.folderTitle)).toEqual(['dailyBrief', 'dailyBrief', undefined]);
+ expect(result.map((d) => d.parentId)).toEqual(['folder-doc', 'folder-doc', undefined]);
+ });
+
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.ts
index 69c4364ad35..2c93705ae7c 100644
--- a/src/utils/agentDocumentContextMapping.ts
+++ b/src/utils/agentDocumentContextMapping.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import {
AGENT_DOCUMENT_INJECTION_POSITIONS,
type AgentContextDocument,
@@ -41,6 +42,7 @@ export const toAgentContextDocument = (doc: AgentDocumentContextPayload): AgentC
doc.policy?.context?.position || doc.policyLoadPosition,
),
loadRules: doc.loadRules,
+ parentId: doc.parentId ?? undefined,
policyId: doc.templateId,
policyLoad: doc.policyLoad,
policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat || undefined,
@@ -60,8 +62,29 @@ export const toAgentContextDocument = (doc: AgentDocumentContextPayload): AgentC
* blocks (). `AgentContextDocument` deliberately has no `fileType`
* field, so the folder check has to happen here, at the DB→context boundary,
* where the derived `isFolder` flag is still available.
+ *
+ * Before dropping them, we harvest the `custom/folder` rows into a
+ * `documentId β†’ title` map and stamp each child's `folderTitle` (matched on
+ * `parentId`). This is the only layer that sees both id-spaces at once β€” a
+ * child's `parentId` points at the folder's `documentId` (`documents.id`),
+ * while the surviving context docs are keyed by their own `agentDocuments.id`
+ * β€” so folder-title resolution has to happen here, not in the injector. The
+ * progressive index then folds same-folder siblings into one summary row
+ * without ever consuming the folder body's token budget (LOBE-11072).
*/
export const toAgentContextDocuments = (
docs: AgentDocumentContextPayload[],
-): AgentContextDocument[] =>
- docs.filter((doc) => !doc.isFolder).map((doc) => toAgentContextDocument(doc));
+): AgentContextDocument[] => {
+ const folderTitleById = new Map<string, string>();
+ for (const doc of docs) {
+ if (doc.fileType === CUSTOM_FOLDER_FILE_TYPE) folderTitleById.set(doc.documentId, 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;
+ });
+};