🤯 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
⚡️ perf: optimize agent document list query (#15904)
Arvin Xua94b3a4ce26a
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex 983ddcb2711..2403bbd9feb 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -98,6 +98,8 @@ describe('AgentDocumentsService', () => {findByFilename: vi.fn(),findSkillDocsByAgent: vi.fn(),hasByAgent: vi.fn(),+ listByAgent: vi.fn(),+ listByDocumentIds: vi.fn(),rename: vi.fn(),update: vi.fn(),upsert: vi.fn(),@@ -282,21 +284,19 @@ describe('AgentDocumentsService', () => {describe('listDocuments', () => {it('should return a list of documents with documentId, filename, id, and title', async () => {- mockModel.findByAgent.mockResolvedValue([+ mockModel.listByAgent.mockResolvedValue([{- content: 'c1',documentId: 'documents-1',filename: 'a.md',id: 'doc-1',- policy: null,+ loadPosition: undefined,title: 'A',},{- content: 'c2',documentId: 'documents-2',filename: 'b.md',id: 'doc-2',- policy: null,+ loadPosition: undefined,title: 'B',},]);@@ -304,7 +304,8 @@ describe('AgentDocumentsService', () => {const service = new AgentDocumentsService(db, userId);const result = await service.listDocuments('agent-1');- expect(mockModel.findByAgent).toHaveBeenCalledWith('agent-1');+ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1');+ expect(mockModel.findByAgent).not.toHaveBeenCalled();expect(result).toEqual([{documentId: 'documents-1',@@ -322,6 +323,16 @@ describe('AgentDocumentsService', () => {},]);});++ it('should pass sourceType filtering to the model', async () => {+ mockModel.listByAgent.mockResolvedValue([]);++ const service = new AgentDocumentsService(db, userId);+ await service.listDocuments('agent-1', 'web');++ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', { sourceType: 'web' });+ expect(mockModel.findByAgent).not.toHaveBeenCalled();+ });});describe('listDocumentsForTopic', () => {@@ -330,19 +341,19 @@ describe('AgentDocumentsService', () => {{ id: 'documents-2', title: 'B' },{ id: 'documents-1', title: 'A' },]);- mockModel.findByDocumentIds.mockResolvedValue([+ mockModel.listByDocumentIds.mockResolvedValue([{documentId: 'documents-1',filename: 'a.md',id: 'agent-doc-1',- policy: null,+ loadPosition: undefined,title: 'A',},{documentId: 'documents-2',filename: 'b.md',id: 'agent-doc-2',- policy: null,+ loadPosition: undefined,title: 'B',},]);@@ -351,10 +362,11 @@ describe('AgentDocumentsService', () => {const result = await service.listDocumentsForTopic('agent-1', 'topic-1');expect(mockTopicDocumentModel.findByTopicId).toHaveBeenCalledWith('topic-1');- expect(mockModel.findByDocumentIds).toHaveBeenCalledWith('agent-1', [+ expect(mockModel.listByDocumentIds).toHaveBeenCalledWith('agent-1', ['documents-2','documents-1',]);+ expect(mockModel.findByDocumentIds).not.toHaveBeenCalled();expect(result).toEqual([{documentId: 'documents-2',@@ -372,6 +384,19 @@ describe('AgentDocumentsService', () => {},]);});++ it('should pass sourceType filtering to the topic document summary query', async () => {+ mockTopicDocumentModel.findByTopicId.mockResolvedValue([{ id: 'documents-1' }]);+ mockModel.listByDocumentIds.mockResolvedValue([]);++ const service = new AgentDocumentsService(db, userId);+ await service.listDocumentsForTopic('agent-1', 'topic-1', 'web');++ expect(mockModel.listByDocumentIds).toHaveBeenCalledWith('agent-1', ['documents-1'], {+ sourceType: 'web',+ });+ expect(mockModel.findByDocumentIds).not.toHaveBeenCalled();+ });});describe('getDocumentByFilename', () => {diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex 4360bfa82bb..10697d4d835 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -13,6 +13,8 @@ import type {AgentDocument,AgentDocumentContextPayload,AgentDocumentContextRow,+ AgentDocumentListItem,+ AgentDocumentListSourceType,AgentDocumentWithRules,ToolUpdateLoadRule,} from '@/database/models/agentDocuments';@@ -611,54 +613,27 @@ export class AgentDocumentsService {}}- async listDocuments(agentId: string, sourceType?: 'all' | 'file' | 'web') {- const docs = await this.agentDocumentModel.findByAgent(agentId);- const filtered =- sourceType && sourceType !== 'all' ? docs.filter((d) => d.sourceType === sourceType) : docs;- return filtered.map((d) => ({- ...deriveAgentDocumentFields(d),- description: d.description,- documentId: d.documentId,- fileType: d.fileType,- filename: d.filename,- id: d.id,- loadPosition: d.policy?.context?.position,- parentId: d.parentId,- sourceType: d.sourceType,- templateId: d.templateId,- title: d.title,- updatedAt: d.updatedAt,- }));+ async listDocuments(agentId: string, sourceType?: AgentDocumentListSourceType) {+ if (!sourceType) return this.agentDocumentModel.listByAgent(agentId);++ return this.agentDocumentModel.listByAgent(agentId, { sourceType });}async listDocumentsForTopic(agentId: string,topicId: string,- sourceType?: 'all' | 'file' | 'web',+ sourceType?: AgentDocumentListSourceType,) {const topicDocs = await this.topicDocumentModel.findByTopicId(topicId);const documentIds = topicDocs.map((doc) => doc.id);- const docs = await this.agentDocumentModel.findByDocumentIds(agentId, documentIds);+ const docs = sourceType+ ? await this.agentDocumentModel.listByDocumentIds(agentId, documentIds, { sourceType })+ : await this.agentDocumentModel.listByDocumentIds(agentId, documentIds);const docsByDocumentId = new Map(docs.map((doc) => [doc.documentId, doc]));return topicDocs.map((topicDoc) => docsByDocumentId.get(topicDoc.id))- .filter((doc): doc is AgentDocumentWithRules => Boolean(doc))- .filter((doc) => !sourceType || sourceType === 'all' || doc.sourceType === sourceType)- .map((doc) => ({- ...deriveAgentDocumentFields(doc),- description: doc.description,- documentId: doc.documentId,- fileType: doc.fileType,- filename: doc.filename,- id: doc.id,- loadPosition: doc.policy?.context?.position,- parentId: doc.parentId,- sourceType: doc.sourceType,- templateId: doc.templateId,- title: doc.title,- updatedAt: doc.updatedAt,- }));+ .filter((doc): doc is AgentDocumentListItem => Boolean(doc));}async getDocumentByFilename(agentId: string, filename: string) {diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex babde6a50bd..17873ccd22b 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -361,6 +361,32 @@ describe('AgentDocumentModel', () => {expect(result.map((doc) => doc.id)).toEqual([ownDoc.id]);});++ it('should list current-agent document summaries by underlying document ids', async () => {+ const ownDoc = await agentDocumentModel.create(agentId, 'own.md', 'own content', {+ sourceType: 'file',+ });+ const webDoc = await agentDocumentModel.create(agentId, 'web-page', 'web content', {+ fileType: 'article',+ sourceType: 'web',+ });+ const secondAgentDoc = await agentDocumentModel.create(+ secondAgentId,+ 'second.md',+ 'second content',+ { sourceType: 'file' },+ );++ const result = await agentDocumentModel.listByDocumentIds(+ agentId,+ [ownDoc.documentId, webDoc.documentId, secondAgentDoc.documentId],+ { sourceType: 'file' },+ );++ expect(result.map((doc) => doc.id)).toEqual([ownDoc.id]);+ expect(result[0]).not.toHaveProperty('content');+ expect(result[0]).not.toHaveProperty('editorData');+ });});describe('update and upsert', () => {@@ -733,6 +759,48 @@ describe('AgentDocumentModel', () => {expect(byTemplate.every((item) => item.templateId === 'claw')).toBe(true);});+ it('should list document summaries without content or editor data', async () => {+ const fileDoc = await agentDocumentModel.create(agentId, 'file.md', 'file content', {+ editorData: { root: { children: [{ text: 'file content' }] } },+ loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,+ sourceType: 'file',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ await agentDocumentModel.create(agentId, 'web-page', 'web content', {+ fileType: 'article',+ sourceType: 'web',+ updatedAt: new Date('2026-01-01T00:00:01.000Z'),+ });+ await agentDocumentModel.create(secondAgentId, 'other-agent.md', 'other content', {+ sourceType: 'file',+ });++ const all = await agentDocumentModel.listByAgent(agentId);++ expect(all.map((item) => item.filename)).toEqual(['web-page', 'file.md']);+ for (const item of all) {+ expect(item).not.toHaveProperty('content');+ expect(item).not.toHaveProperty('editorData');+ }++ const fileSummary = all.find((item) => item.id === fileDoc.id);+ expect(fileSummary).toMatchObject({+ category: 'document',+ documentId: fileDoc.documentId,+ filename: 'file.md',+ id: fileDoc.id,+ isFolder: false,+ isSkillBundle: false,+ isSkillIndex: false,+ loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,+ sourceType: 'file',+ title: 'file',+ });++ const webOnly = await agentDocumentModel.listByAgent(agentId, { sourceType: 'web' });+ expect(webOnly.map((item) => item.filename)).toEqual(['web-page']);+ });+it('should return only skill-managed docs for skill registry assembly', async () => {const bundle = await agentDocumentModel.create(agentId, 'bug-triage', 'bundle body', {fileType: SKILL_BUNDLE_FILE_TYPE,diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex 32c8cefcd2c..f2281a94097 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -18,6 +18,8 @@ import {import type {AgentDocument,AgentDocumentContextRow,+ AgentDocumentListItem,+ AgentDocumentListSourceType,AgentDocumentPolicy,AgentDocumentSourceType,AgentDocumentWithRules,@@ -70,6 +72,20 @@ interface ConvertAgentDocumentToSkillIndexParams {title: string;}+interface AgentDocumentListQueryRow {+ description: string | null;+ documentId: string;+ filename: string | null;+ fileType: string;+ id: string;+ parentId: string | null;+ policy: unknown;+ sourceType: AgentDocumentSourceType;+ templateId: string | null;+ title: string | null;+ updatedAt: Date;+}+export class AgentDocumentModel {private userId: string;private workspaceId?: string;@@ -164,6 +180,29 @@ export class AgentDocumentModel {};}+ private toAgentDocumentListItem(row: AgentDocumentListQueryRow): AgentDocumentListItem {+ const filename = row.filename ?? '';+ const policy = (row.policy as AgentDocumentPolicy | null) ?? null;+ const item = {+ description: row.description ?? null,+ documentId: row.documentId,+ fileType: row.fileType,+ filename,+ id: row.id,+ loadPosition: policy?.context?.position,+ parentId: row.parentId ?? null,+ sourceType: row.sourceType,+ templateId: row.templateId ?? null,+ title: row.title ?? filename,+ updatedAt: row.updatedAt,+ };++ return {+ ...item,+ ...deriveAgentDocumentFields(item),+ };+ }+private buildDeletedAtFilters(options?: AgentDocumentQueryOptions) {if (options?.deletedOnly) return [isNotNull(agentDocuments.deletedAt)];if (options?.includeDeleted) return [];@@ -910,6 +949,40 @@ export class AgentDocumentModel {});}+ async listByAgent(+ agentId: string,+ options?: { sourceType?: AgentDocumentListSourceType },+ ): Promise<AgentDocumentListItem[]> {+ const sourceType = options?.sourceType;+ const results = await this.db+ .select({+ description: documents.description,+ documentId: agentDocuments.documentId,+ fileType: documents.fileType,+ filename: documents.filename,+ id: agentDocuments.id,+ parentId: documents.parentId,+ policy: agentDocuments.policy,+ sourceType: documents.sourceType,+ templateId: agentDocuments.templateId,+ title: documents.title,+ updatedAt: agentDocuments.updatedAt,+ })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ this.agentDocOwnership(),+ eq(agentDocuments.agentId, agentId),+ isNull(agentDocuments.deletedAt),+ ...(sourceType && sourceType !== 'all' ? [eq(documents.sourceType, sourceType)] : []),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map((row) => this.toAgentDocumentListItem(row));+ }+async findSkillDocsByAgent(agentId: string): Promise<AgentDocumentWithRules[]> {const results = await this.db.select({ doc: documents, settings: agentDocuments })@@ -1053,6 +1126,44 @@ export class AgentDocumentModel {});}+ async listByDocumentIds(+ agentId: string,+ documentIds: string[],+ options?: { sourceType?: AgentDocumentListSourceType },+ ): Promise<AgentDocumentListItem[]> {+ if (documentIds.length === 0) return [];++ const sourceType = options?.sourceType;+ const results = await this.db+ .select({+ description: documents.description,+ documentId: agentDocuments.documentId,+ fileType: documents.fileType,+ filename: documents.filename,+ id: agentDocuments.id,+ parentId: documents.parentId,+ policy: agentDocuments.policy,+ sourceType: documents.sourceType,+ templateId: agentDocuments.templateId,+ title: documents.title,+ updatedAt: agentDocuments.updatedAt,+ })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ this.agentDocOwnership(),+ eq(agentDocuments.agentId, agentId),+ inArray(agentDocuments.documentId, documentIds),+ isNull(agentDocuments.deletedAt),+ ...(sourceType && sourceType !== 'all' ? [eq(documents.sourceType, sourceType)] : []),+ ),+ )+ .orderBy(desc(agentDocuments.updatedAt));++ return results.map((row) => this.toAgentDocumentListItem(row));+ }+async hasByAgent(agentId: string): Promise<boolean> {const [result] = await this.db.select({ id: agentDocuments.id })diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.tsindex 134e747a280..e7ff1976516 100644--- a/packages/database/src/models/agentDocuments/types.ts+++ b/packages/database/src/models/agentDocuments/types.ts@@ -6,6 +6,7 @@import type {AgentDocumentPolicy,DocumentLoadFormat,+ DocumentLoadPosition as DocumentLoadPositionType,DocumentLoadRules,PolicyLoad,} from '@lobechat/agent-templates';@@ -23,6 +24,7 @@ export {export type { AgentDocumentPolicy, DocumentLoadRules } from '@lobechat/agent-templates';export type AgentDocumentSourceType = 'file' | 'web' | 'api' | 'topic' | 'agent' | 'agent-signal';+export type AgentDocumentListSourceType = 'all' | 'file' | 'web';/*** UI-facing tab grouping for an agent document. Derived from `fileType` +@@ -81,6 +83,20 @@ export interface AgentDocumentWithRules extends AgentDocument, AgentDocumentDeriloadRules: DocumentLoadRules;}+export interface AgentDocumentListItem extends AgentDocumentDerivedFields {+ description: string | null;+ documentId: string;+ filename: string;+ fileType: string;+ id: string;+ loadPosition: DocumentLoadPositionType | undefined;+ parentId: string | null;+ sourceType: AgentDocumentSourceType;+ templateId: string | null;+ title: string;+ updatedAt: Date;+}+export interface AgentDocumentContextRow extends AgentDocumentDerivedFields {content: string;contentCharCount?: number;