π€― 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
π fix(knowledge-base): read uploaded agent-document files instead of their empty placeholder (#20082)
Arvin Xuf37974d1132b
diff --git a/apps/server/src/services/knowledgeBase/index.test.ts b/apps/server/src/services/knowledgeBase/index.test.tsindex a454239b233..3641806fab4 100644--- a/apps/server/src/services/knowledgeBase/index.test.ts+++ b/apps/server/src/services/knowledgeBase/index.test.ts@@ -90,6 +90,77 @@ describe('KnowledgeBaseSearchService', () => {expect(result[0].error).toBeUndefined();});+ describe('file-backed agent documents (uploaded into the Documents panel)', () => {+ // `AgentDocumentsService.importFile` stores the bytes in `files` and writes an empty+ // `documents` row pointing at them; only the original file holds the text.+ const placeholder = {+ content: '',+ fileId: 'file_RievR3MzZrMG',+ fileType: 'text/markdown',+ filename: 'product-spec.md',+ id: 'docs_sq6UdPi9clb74C4e',+ metadata: null,+ sourceType: 'file',+ title: 'product-spec.md',+ totalCharCount: 0,+ };++ it('reads docs_* through the underlying file instead of the empty placeholder', async () => {+ documentModelMock.findById.mockResolvedValue(placeholder);+ fileModelMock.findById.mockResolvedValue({+ id: 'file_RievR3MzZrMG',+ name: 'product-spec.md',+ });+ documentModelMock.findByFileId.mockResolvedValue(undefined);+ documentServiceMock.parseFile.mockResolvedValue({+ content: '# Product Spec\n\nShip the uploader.',+ metadata: null,+ });++ const result = await service.getFileContents(['docs_sq6UdPi9clb74C4e']);++ expect(fileModelMock.findById).toHaveBeenCalledWith('file_RievR3MzZrMG');+ expect(documentServiceMock.parseFile).toHaveBeenCalledWith('file_RievR3MzZrMG');+ expect(result[0]).toMatchObject({+ content: '# Product Spec\n\nShip the uploader.',+ fileId: 'docs_sq6UdPi9clb74C4e',+ filename: 'product-spec.md',+ totalCharCount: 34,+ });+ expect(result[0].error).toBeUndefined();+ });++ it('reuses an existing parse cache for the placeholder file', async () => {+ documentModelMock.findById.mockResolvedValue(placeholder);+ fileModelMock.findById.mockResolvedValue({+ id: 'file_RievR3MzZrMG',+ name: 'product-spec.md',+ });+ documentModelMock.findByFileId.mockResolvedValue({+ content: 'cached parse',+ metadata: null,+ });++ const result = await service.getFileContents(['docs_sq6UdPi9clb74C4e']);++ expect(documentServiceMock.parseFile).not.toHaveBeenCalled();+ expect(result[0]).toMatchObject({ content: 'cached parse', totalCharCount: 12 });+ });++ it('keeps reading an edited docs_* row that happens to reference a file', async () => {+ documentModelMock.findById.mockResolvedValue({+ ...placeholder,+ content: 'hand-written notes',+ fileType: 'custom/document',+ });++ const result = await service.getFileContents(['docs_sq6UdPi9clb74C4e']);++ expect(fileModelMock.findById).not.toHaveBeenCalled();+ expect(result[0].content).toBe('hand-written notes');+ });+ });+it('returns "Document not found" when docs_* id is missing', async () => {documentModelMock.findById.mockResolvedValue(undefined);diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.tsindex 2c656ac8701..ded68d39579 100644--- a/apps/server/src/services/knowledgeBase/index.ts+++ b/apps/server/src/services/knowledgeBase/index.ts@@ -14,6 +14,7 @@ import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';import type { FtsSearchKnowledgeBaseDocumentHit } from '@/database/repositories/ftsSearch';import { knowledgeBaseFiles } from '@/database/schemas';+import { isFileBackedPlaceholder } from '@/database/utils/fileBackedPlaceholder';import { readOriginalCharCount } from '@/database/utils/parsedDocument';import { buildWorkspaceWhere } from '@/database/utils/workspace';import { getServerDefaultFilesConfig } from '@/server/globalConfig';@@ -244,6 +245,14 @@ export class KnowledgeBaseSearchService {filename: `Unknown document ${id}`,};}+ // A file uploaded into an agent's Documents panel is an empty row pointing at the+ // original file; its text only exists once the file is parsed.+ if (isFileBackedPlaceholder(doc)) {+ return this.readFileContent(doc.fileId!, {+ filename: doc.title || doc.filename || undefined,+ resultId: id,+ });+ }const content = doc.content ?? '';const lines = content.split('\n');return {@@ -259,46 +268,59 @@ export class KnowledgeBaseSearchService {}// ---- Branch B: file_* β original file/parse path ----- const file = await this.fileModel.findById(id);- if (!file) {- return {- content: '',- error: 'File not found',- fileId: id,- filename: `Unknown file ${id}`,- };- }+ return this.readFileContent(id, { resultId: id });+ },+ { concurrency: 3 },+ );+ }- let document: { content: string | null; metadata: Record<string, any> | null } | undefined =- await this.documentModel.findByFileId(id);+ /**+ * Read a file's parsed text, parsing it on first read.+ *+ * `resultId` is echoed back as `fileId` so callers can match results to the ids they asked for.+ */+ private async readFileContent(+ fileId: string,+ { filename, resultId }: { filename?: string; resultId: string },+ ): Promise<FileContentResult> {+ const file = await this.fileModel.findById(fileId);+ if (!file) {+ return {+ content: '',+ error: 'File not found',+ fileId: resultId,+ filename: filename ?? `Unknown file ${resultId}`,+ };+ }- if (!document) {- try {- document = await this.documentService.parseFile(id);- } catch (error) {- return {- content: '',- error: `Failed to parse file: ${(error as Error).message}`,- fileId: id,- filename: file.name,- };- }- }+ // `findByFileId` skips agent-document placeholders, so a hit is always parsed text.+ let document: { content: string | null; metadata: Record<string, any> | null } | undefined =+ await this.documentModel.findByFileId(fileId);- const content = document.content || '';- const lines = content.split('\n');+ if (!document) {+ try {+ document = await this.documentService.parseFile(fileId);+ } catch (error) {return {- content,- fileId: id,- filename: file.name,- metadata: document.metadata,- originalCharCount: readOriginalCharCount(document.metadata),- preview: lines.slice(0, 5).join('\n'),- totalCharCount: content.length,- totalLineCount: lines.length,+ content: '',+ error: `Failed to parse file: ${(error as Error).message}`,+ fileId: resultId,+ filename: filename ?? file.name,};- },- { concurrency: 3 },- );+ }+ }++ const content = document.content || '';+ const lines = content.split('\n');+ return {+ content,+ fileId: resultId,+ filename: filename ?? file.name,+ metadata: document.metadata,+ originalCharCount: readOriginalCharCount(document.metadata),+ preview: lines.slice(0, 5).join('\n'),+ totalCharCount: content.length,+ totalLineCount: lines.length,+ };}}diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 7b42f8981ac..aae81bdb527 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -194,6 +194,41 @@ describe('AgentModel', () => {expect(result!.files[0].content).toBe('parse cache');});+ it('should skip an agent-document upload placeholder in favor of the parse cache', async () => {+ const agentId = 'test-agent-with-placeholder';+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(agentsFiles).values({ agentId, fileId: '1', userId, enabled: true });+ // Older empty row written by `AgentDocumentsService.importFile`; bytes live in the file.+ await serverDB.insert(documents).values({+ content: '',+ createdAt: new Date('2026-01-01'),+ fileId: '1',+ fileType: 'text/markdown',+ id: 'doc-placeholder',+ source: 'notes.md',+ sourceType: 'file',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ });+ await serverDB.insert(documents).values({+ content: 'parsed notes',+ createdAt: new Date('2026-02-01'),+ fileId: '1',+ fileType: 'custom/document',+ id: 'doc-parsed',+ source: 'notes.md',+ sourceType: 'file',+ totalCharCount: 12,+ totalLineCount: 1,+ userId,+ });++ const result = await agentModel.getAgentConfigById(agentId);++ expect(result!.files[0].content).toBe('parsed notes');+ });+it('should not include content for disabled files', async () => {const agentId = 'test-agent-disabled-file';await serverDB.insert(agents).values({ id: agentId, userId });diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex e0342b9b6cf..a624014ecf9 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -923,6 +923,77 @@ describe('DocumentModel', () => {expect(found?.id).toBe('document-tie-a');});+ describe('file-backed agent-document placeholder', () => {+ const createUploadedMarkdown = async () => {+ const { id } = await fileModel.create({+ fileType: 'text/markdown',+ name: 'product-spec.md',+ size: 329_028,+ url: 'files/product-spec.md',+ });+ const file = await fileModel.findById(id);+ if (!file) throw new Error('File not found after creation');+ return file;+ };++ // Shape `AgentDocumentsService.importFile` writes: empty content, the file's own MIME type.+ const insertPlaceholder = (fileId: string, url: string) =>+ documentModel.create({+ content: '',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ fileId,+ fileType: 'text/markdown',+ filename: 'product-spec.md',+ source: url,+ sourceType: 'file',+ title: 'product-spec.md',+ totalCharCount: 0,+ totalLineCount: 0,+ });++ it('should not treat the placeholder as a parse result', async () => {+ const file = await createUploadedMarkdown();+ await insertPlaceholder(file.id, file.url);++ await expect(documentModel.findByFileId(file.id)).resolves.toBeUndefined();+ });++ it('should return the parse cache written after the placeholder', async () => {+ const file = await createUploadedMarkdown();+ await insertPlaceholder(file.id, file.url);+ const { id: parsedId } = await documentModel.create({+ content: '# Product Spec',+ createdAt: new Date('2026-01-02T00:00:00.000Z'),+ fileId: file.id,+ fileType: 'custom/document',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 14,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(file.id);+ expect(found?.id).toBe(parsedId);+ expect(found?.content).toBe('# Product Spec');+ });++ it('should still return a parse cache of an empty file', async () => {+ const file = await createUploadedMarkdown();+ const { id: parsedId } = await documentModel.create({+ content: '',+ fileId: file.id,+ fileType: 'custom/document',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 0,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(file.id);+ expect(found?.id).toBe(parsedId);+ });+ });+it('should handle different file types', async () => {const { id: pdfFileId } = await fileModel.create({fileType: 'application/pdf',diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 263702bb70a..79aededec4a 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -2560,6 +2560,60 @@ describe('MessageModel Query Tests', () => {const [byId] = await messageModel.queryByIds([messageId]);expect(byId.fileList![0].content).toBe('parse cache');});++ it('should skip an agent-document upload placeholder in favor of the parse cache', async () => {+ const fileId = uuid();+ const messageId = uuid();+ const doc = {+ fileId,+ source: 'notes.md',+ sourceType: 'file',+ totalLineCount: 1,+ userId,+ } as const;++ await serverDB.transaction(async (trx) => {+ await trx.insert(sessions).values({ id: 'session1', userId });+ await trx.insert(files).values({+ fileType: 'text/markdown',+ id: fileId,+ name: 'notes.md',+ size: 100,+ url: 'notes.md',+ userId,+ });+ // Older empty row written by `AgentDocumentsService.importFile`; bytes live in the file.+ await trx.insert(documents).values({+ ...doc,+ content: '',+ createdAt: new Date('2026-01-01'),+ fileType: 'text/markdown',+ totalCharCount: 0,+ });+ await trx.insert(documents).values({+ ...doc,+ content: 'parse cache',+ createdAt: new Date('2026-02-01'),+ fileType: 'custom/document',+ totalCharCount: 11,+ });++ await trx.insert(messages).values({+ content: 'Message with an uploaded agent document',+ id: messageId,+ role: 'user',+ sessionId: 'session1',+ userId,+ });+ await trx.insert(messagesFiles).values({ fileId, messageId, userId });+ });++ const result = await messageModel.query({ sessionId: 'session1' });+ expect(result[0].fileList![0].content).toBe('parse cache');++ const [byId] = await messageModel.queryByIds([messageId]);+ expect(byId.fileList![0].content).toBe('parse cache');+ });});describe('query messages with threadId filter', () => {diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 07f3a47ed67..736c3e07bf5 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -82,6 +82,7 @@ import {} from '../utils/agentKnowledgeMounts';import { rehomeAgentLabelsForRecipient } from '../utils/agentLabelsOwnership';import { rehomeAgentQuotaBindingsForRecipient } from '../utils/agentQuotaBindings';+import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { resolveGroupMembershipType } from '../utils/groupMembership';import { normalizeInboxAgentMeta } from '../utils/inboxAgent';@@ -794,7 +795,11 @@ export class AgentModel {// A file can own several documents; take the oldest, like `DocumentModel.findByFileId`// (which `readAttachment` pages through), so the preview and its continuation agree.orderBy: [asc(documents.createdAt), asc(documents.id)],- where: and(this.documentsOwnership(), inArray(documents.fileId, enabledFileIds)),+ where: and(+ this.documentsOwnership(),+ inArray(documents.fileId, enabledFileIds),+ notFileBackedPlaceholder(),+ ),});const documentMap = new Map<string | null, (typeof documentsData)[number]>();diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex fbf790ec472..cd62b9b4298 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -36,6 +36,7 @@ import {} from '../schemas';import type { LobeChatDatabase } from '../type';import { documentMatchesAccessScope } from '../utils/documentVisibility';+import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';import {fileReferenceMatchesAccessScope,notAgentShareFileReference,@@ -363,10 +364,13 @@ export class DocumentModel {// Pick the oldest one explicitly instead of leaving the choice to the// query plan, so repeated lookups keep returning the same content.// `created_at` carries no uniqueness guarantee, so `id` breaks ties.+ // An agent-document upload's empty placeholder row holds no text, so it is+ // never the file's parse result; skipping it lets `parseFile` run..where(and(this.ownership(),eq(documents.fileId, fileId),+ notFileBackedPlaceholder(),fileReferenceMatchesAccessScope(this.db, documents.fileId, accessScope),),)diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 9a5b072bb41..7ebf9d127a6 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -95,6 +95,7 @@ import {import type { LobeChatDatabase, Transaction } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { notCopiedTranscript } from '../utils/copiedTranscript';+import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';import { inJsonStringArray } from '../utils/inJsonStringArray';@@ -1937,7 +1938,7 @@ export class MessageModel {this.db.select(fileDocumentColumns).from(documents)- .where(inArray(documents.fileId, fileIds))+ .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder())).orderBy(...fileDocumentsOrder),{ fileCount: fileIds.length },);@@ -2322,7 +2323,7 @@ export class MessageModel {const documentsList = await this.db.select(fileDocumentColumns).from(documents)- .where(inArray(documents.fileId, fileIds))+ .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder())).orderBy(...fileDocumentsOrder);documentsMap = toFileDocumentsMap(documentsList);diff --git a/packages/database/src/utils/fileBackedPlaceholder.ts b/packages/database/src/utils/fileBackedPlaceholder.tsnew file mode 100644index 00000000000..33e8434b01a--- /dev/null+++ b/packages/database/src/utils/fileBackedPlaceholder.ts@@ -0,0 +1,36 @@+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import type { SQL } from 'drizzle-orm';+import { sql } from 'drizzle-orm';++import { documents } from '../schemas';++interface FileBackedPlaceholderFields {+ content?: string | null;+ fileId?: string | null;+ fileType?: string | null;+ sourceType?: string | null;+}++/**+ * Whether a `documents` row is the empty binding an agent-document upload writes for its file.+ *+ * `AgentDocumentsService.importFile` keeps the uploaded bytes in `files` and inserts an empty+ * `documents` row (`sourceType: 'file'`, the file's own MIME type) so the Documents tree can list and+ * preview the original. That row carries no text: readers wanting the file's text must parse the+ * file instead. Parse results (`parseFile` / `parseDocument`) are stored as `custom/document`, so an+ * empty parse of an empty file is still a real result, not a placeholder.+ */+export const isFileBackedPlaceholder = (doc: FileBackedPlaceholderFields): boolean =>+ doc.sourceType === 'file' &&+ !!doc.fileId &&+ !doc.content &&+ doc.fileType !== CUSTOM_DOCUMENT_FILE_TYPE;++/** SQL twin of {@link isFileBackedPlaceholder}: rows holding the file's text, not its placeholder. */+export const notFileBackedPlaceholder = (): SQL<boolean> =>+ sql<boolean>`NOT (+ ${documents.sourceType} = 'file'+ AND ${documents.fileId} IS NOT NULL+ AND COALESCE(${documents.content}, '') = ''+ AND ${documents.fileType} IS DISTINCT FROM ${CUSTOM_DOCUMENT_FILE_TYPE}+ )`;