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.

🐛 fix(agent): preserve archived tool results losslessly (#18258)

YuTengjing8c3e59cc0942
diff --git a/apps/server/src/services/agentDocumentVfs/index.test.ts b/apps/server/src/services/agentDocumentVfs/index.test.ts
index 111b65d6f19..27f4b44aafa 100644
--- a/apps/server/src/services/agentDocumentVfs/index.test.ts
+++ b/apps/server/src/services/agentDocumentVfs/index.test.ts
@@ -1,10 +1,11 @@
// @vitest-environment node
import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentAccess, AgentDocumentModel } from '@/database/models/agentDocuments';
import type { LobeChatDatabase } from '@/database/type';
+import * as headlessEditor from '../agentDocuments/headlessEditor';
import { AgentDocumentVfsService } from './index';
import { createSkillMount } from './mounts/skills/createSkillMount';
@@ -65,6 +66,10 @@ describe('AgentDocumentVfsService', () => {
});
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it('lists ordinary root nodes plus the synthetic lobe directory', async () => {
mockAgentDocumentModel.listByParent.mockResolvedValue([
{
@@ -289,6 +294,81 @@ describe('AgentDocumentVfsService', () => {
);
});
+ it('stores raw ordinary file content without Markdown serialization', async () => {
+ const content = `<knowledge_base_files totalCount="1">
+<file id="file-1" name="raw.txt">
+${'lossless tool result\n'.repeat(100)}
+</file>
+</knowledge_base_files>`;
+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);
+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([]);
+ mockAgentDocumentModel.create.mockResolvedValue({
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content,
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ documentId: 'documents-raw',
+ fileType: 'text/plain',
+ filename: 'archive.txt',
+ id: 'agent-doc-raw',
+ metadata: null,
+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),
+ });
+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createMarkdownEditorSnapshot');
+ const service = new AgentDocumentVfsService(db, userId);
+ const node = await service.write(
+ './archive.txt',
+ content,
+ { agentId: 'agent-1' },
+ {
+ contentFormat: 'raw',
+ },
+ );
+
+ expect(createSnapshotSpy).not.toHaveBeenCalled();
+ expect(node.contentType).toBe('text/plain');
+ expect(mockAgentDocumentModel.create).toHaveBeenCalledWith('agent-1', 'archive.txt', content, {
+ fileType: 'text/plain',
+ parentId: null,
+ title: 'archive.txt',
+ });
+ });
+
+ it('overwrites raw ordinary file content without Markdown serialization', async () => {
+ const existing = {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'old content',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ documentId: 'documents-raw',
+ fileType: 'text/plain',
+ filename: 'archive.txt',
+ id: 'agent-doc-raw',
+ metadata: null,
+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),
+ };
+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existing);
+ mockAgentDocumentModel.update.mockImplementation(async (_id, params) => {
+ Object.assign(existing, params);
+ });
+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createMarkdownEditorSnapshot');
+ const service = new AgentDocumentVfsService(db, userId);
+
+ await service.write(
+ './archive.txt',
+ 'new raw content',
+ { agentId: 'agent-1' },
+ {
+ contentFormat: 'raw',
+ },
+ );
+
+ expect(createSnapshotSpy).not.toHaveBeenCalled();
+ expect(mockAgentDocumentModel.update).toHaveBeenCalledWith('agent-doc-raw', {
+ content: 'new raw content',
+ editorData: null,
+ fileType: 'text/plain',
+ });
+ });
+
it('resolves duplicate ordinary path segments to the oldest sibling', async () => {
mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([
{
diff --git a/apps/server/src/services/agentDocumentVfs/index.ts b/apps/server/src/services/agentDocumentVfs/index.ts
index e41b4c48a60..c524597f3e2 100644
--- a/apps/server/src/services/agentDocumentVfs/index.ts
+++ b/apps/server/src/services/agentDocumentVfs/index.ts
@@ -8,6 +8,10 @@ import {
} from '@/database/models/agentDocuments';
import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';
+import {
+ getAgentDocumentContentType,
+ RAW_TEXT_DOCUMENT_FILE_TYPE,
+} from '../agentDocuments/contentFormat';
import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';
import { AgentDocumentVfsError } from './errors';
import { createSkillMount } from './mounts/skills/createSkillMount';
@@ -55,6 +59,11 @@ interface AgentDocumentVfsContext {
}
interface AgentDocumentWriteOptions {
+ /**
+ * Raw writes bypass the Markdown editor snapshot because arbitrary tool or code output may
+ * contain markup that the editor legitimately normalizes or discards.
+ */
+ contentFormat?: 'markdown' | 'raw';
createMode?: 'always-new' | 'if-missing' | 'must-exist';
}
@@ -241,7 +250,7 @@ export class AgentDocumentVfsService {
return {
...sliceReadContent(node.content, options.loc),
- contentType: 'text/markdown',
+ contentType: getAgentDocumentContentType(node),
path: normalizedPath,
};
}
@@ -272,7 +281,13 @@ export class AgentDocumentVfsService {
return this.writeMountedSkill(normalizedPath, content, ctx, createMode);
}
- return this.writeOrdinaryDocument(normalizedPath, content, ctx, createMode);
+ return this.writeOrdinaryDocument(
+ normalizedPath,
+ content,
+ ctx,
+ createMode,
+ options.contentFormat ?? 'markdown',
+ );
}
/**
@@ -780,6 +795,7 @@ export class AgentDocumentVfsService {
content: string,
ctx: AgentDocumentVfsContext,
createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,
+ contentFormat: NonNullable<AgentDocumentWriteOptions['contentFormat']>,
): Promise<AgentDocumentStats> {
if (path === './' || path === LOBE_PATH || path.startsWith(`${LOBE_PATH}/`)) {
throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');
@@ -798,11 +814,19 @@ export class AgentDocumentVfsService {
throw new AgentDocumentVfsError(`Path already exists: ${writablePath}`, 'BAD_REQUEST');
}
- const snapshot = await createMarkdownEditorSnapshot(content);
- await this.agentDocumentModel.update(existing.id, {
- content: snapshot.content,
- editorData: snapshot.editorData,
- });
+ if (contentFormat === 'raw') {
+ await this.agentDocumentModel.update(existing.id, {
+ content,
+ editorData: null,
+ fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,
+ });
+ } else {
+ const snapshot = await createMarkdownEditorSnapshot(content);
+ await this.agentDocumentModel.update(existing.id, {
+ content: snapshot.content,
+ editorData: snapshot.editorData,
+ });
+ }
const updated = await this.resolveOrdinaryPath(writablePath, ctx.agentId);
@@ -843,6 +867,21 @@ export class AgentDocumentVfsService {
}
const normalizedFilename = buildDocumentFilename(filename);
+ if (contentFormat === 'raw') {
+ const created = await this.agentDocumentModel.create(
+ ctx.agentId,
+ normalizedFilename,
+ content,
+ {
+ fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,
+ parentId: parentNode?.documentId ?? null,
+ title: normalizedFilename,
+ },
+ );
+
+ return this.toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));
+ }
+
const snapshot = await createMarkdownEditorSnapshot(content);
const created = await this.agentDocumentModel.create(
ctx.agentId,
@@ -955,7 +994,8 @@ export class AgentDocumentVfsService {
private toOrdinaryStats(doc: AgentDocument, path: string): AgentDocumentStats {
return {
...this.toOrdinaryNode(doc, path),
- contentType: doc.fileType === DOCUMENT_FOLDER_TYPE ? undefined : 'text/markdown',
+ contentType:
+ doc.fileType === DOCUMENT_FOLDER_TYPE ? undefined : getAgentDocumentContentType(doc),
deleteReason: doc.deleteReason,
deletedAt: doc.deletedAt,
metadata: doc.metadata ?? undefined,
diff --git a/apps/server/src/services/agentDocuments/contentFormat.ts b/apps/server/src/services/agentDocuments/contentFormat.ts
new file mode 100644
index 00000000000..4c33e24322a
--- /dev/null
+++ b/apps/server/src/services/agentDocuments/contentFormat.ts
@@ -0,0 +1,11 @@
+export const RAW_TEXT_DOCUMENT_FILE_TYPE = 'text/plain';
+
+interface AgentDocumentContentFormatFields {
+ fileType?: string | null;
+}
+
+export const isRawTextAgentDocument = ({ fileType }: AgentDocumentContentFormatFields): boolean =>
+ fileType === RAW_TEXT_DOCUMENT_FILE_TYPE;
+
+export const getAgentDocumentContentType = (fields: AgentDocumentContentFormatFields): string =>
+ isRawTextAgentDocument(fields) ? RAW_TEXT_DOCUMENT_FILE_TYPE : 'text/markdown';
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.ts
index 2fb52014b4e..96ba6d04ef2 100644
--- a/apps/server/src/services/agentDocuments/index.test.ts
+++ b/apps/server/src/services/agentDocuments/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+import { createHeadlessEditor } from '@lobehub/editor/headless';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentModel } from '@/database/models/agent';
@@ -591,6 +592,38 @@ describe('AgentDocumentsService', () => {
});
});
+ it('should return raw text documents without Markdown projection', async () => {
+ const agentDocumentId = '11111111-1111-4111-8111-111111111111';
+ const content = `<knowledge_base_files totalCount="1">
+<file id="file-1" name="raw.txt">
+lossless tool result
+</file>
+</knowledge_base_files>`;
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content,
+ editorData: null,
+ fileType: 'text/plain',
+ filename: 'topic_call.txt',
+ id: agentDocumentId,
+ title: 'topic_call.txt',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.getDocumentSnapshotById(agentDocumentId, 'agent-1');
+
+ expect(createHeadlessEditor).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ agentId: 'agent-1',
+ content,
+ editorData: null,
+ fileType: 'text/plain',
+ filename: 'topic_call.txt',
+ id: agentDocumentId,
+ title: 'topic_call.txt',
+ });
+ });
+
it('should resolve a backing document id without querying the UUID binding column', async () => {
const agentDocumentId = '11111111-1111-4111-8111-111111111111';
mockModel.findByDocumentId.mockResolvedValue({
diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.ts
index e64f19028d9..b9e68f6994f 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -31,6 +31,7 @@ import { AgentDocumentVfsError } from '../agentDocumentVfs/errors';
import { isManagedSkillDocument } from '../agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
import { DocumentService } from '../document';
import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';
+import { isRawTextAgentDocument } from './contentFormat';
import {
type AgentDocumentLiteXMLOperation,
applyLiteXMLOperations,
@@ -200,6 +201,8 @@ export class AgentDocumentsService {
}
private async attachLiteXML(doc: AgentDocument): Promise<AgentDocumentWithLiteXML> {
+ if (isRawTextAgentDocument(doc)) return doc;
+
const snapshot = await exportEditorDataSnapshot({
editorData: doc.editorData,
fallbackContent: doc.content,
diff --git a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
index 5a0c4d57e64..d971ff8f19e 100644
--- a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts
@@ -19,6 +19,7 @@ describe('archiveToolResultIfNeeded', () => {
const db = {} as LobeChatDatabase;
const mockVfsService = {
mkdir: vi.fn(),
+ read: vi.fn(),
write: vi.fn(),
};
const mockTopicDocumentModel = {
@@ -31,6 +32,7 @@ describe('archiveToolResultIfNeeded', () => {
vi.mocked(AgentDocumentVfsService).mockImplementation(() => mockVfsService as any);
vi.mocked(TopicDocumentModel).mockImplementation(() => mockTopicDocumentModel as any);
mockVfsService.mkdir.mockResolvedValue({});
+ mockVfsService.read.mockResolvedValue({ content: '0123456789' });
mockVfsService.write.mockResolvedValue({ documentId: 'document-1', id: 'agent-doc-1' });
mockTopicDocumentModel.isAssociated.mockResolvedValue(false);
mockTopicDocumentModel.associate.mockResolvedValue({
@@ -74,7 +76,12 @@ describe('archiveToolResultIfNeeded', () => {
'./.tool-results/topic-1_call_1.txt',
'0123456789',
{ agentId: 'agent-1', topicId: 'topic-1' },
+ { contentFormat: 'raw' },
);
+ expect(mockVfsService.read).toHaveBeenCalledWith('./.tool-results/topic-1_call_1.txt', {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({
documentId: 'document-1',
topicId: 'topic-1',
@@ -104,6 +111,25 @@ describe('archiveToolResultIfNeeded', () => {
expect(mockTopicDocumentModel.associate).not.toHaveBeenCalled();
});
+ it('fails closed when the persisted archive content does not match the tool result', async () => {
+ mockVfsService.read.mockResolvedValue({ content: 'corrupted' });
+
+ const result = await archiveToolResultIfNeeded({
+ agentId: 'agent-1',
+ content: '0123456789',
+ limit: 5,
+ serverDB: db,
+ toolCallId: 'call_1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(result.archived).toBe(false);
+ expect(result.error).toBe('Archived content verification failed');
+ expect(result.content).toContain('Archive failed: Archived content verification failed');
+ expect(mockTopicDocumentModel.associate).not.toHaveBeenCalled();
+ });
+
it('falls back to truncation without archive context', async () => {
const result = await archiveToolResultIfNeeded({
agentId: 'agent-1',
diff --git a/apps/server/src/services/toolExecution/archiveToolResult.ts b/apps/server/src/services/toolExecution/archiveToolResult.ts
index a9b055e0fda..614d09e5cc4 100644
--- a/apps/server/src/services/toolExecution/archiveToolResult.ts
+++ b/apps/server/src/services/toolExecution/archiveToolResult.ts
@@ -11,6 +11,7 @@ import {
import { TOOL_RESULTS_DIR_NAME } from './constants';
const TOOL_RESULTS_DIR = `./${TOOL_RESULTS_DIR_NAME}`;
+const ARCHIVE_VERIFICATION_ERROR = 'Archived content verification failed';
export interface ToolResultArchiveOutcome {
archived: boolean;
@@ -69,7 +70,16 @@ export const archiveToolResultIfNeeded = async ({
try {
const vfsService = new AgentDocumentVfsService(serverDB, userId, workspaceId);
await vfsService.mkdir(TOOL_RESULTS_DIR, { agentId, topicId }, { recursive: true });
- const stats = await vfsService.write(archivePath, content, { agentId, topicId });
+ const stats = await vfsService.write(
+ archivePath,
+ content,
+ { agentId, topicId },
+ { contentFormat: 'raw' },
+ );
+ const persisted = await vfsService.read(archivePath, { agentId, topicId });
+
+ // Never tell the model that a full result exists unless the VFS can return it losslessly.
+ if (persisted.content !== content) throw new Error(ARCHIVE_VERIFICATION_ERROR);
if (stats.documentId) {
const topicDocumentModel = new TopicDocumentModel(serverDB, userId, workspaceId);
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 10579a3a21f..cb6ebb27502 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -563,7 +563,8 @@ export class AgentDocumentModel {
documentId: string,
params?: {
content?: string;
- editorData?: Record<string, any>;
+ editorData?: Record<string, any> | null;
+ fileType?: string;
loadPosition?: DocumentLoadPosition;
loadRules?: Partial<DocumentLoadRules>;
metadata?: Record<string, any>;
@@ -571,7 +572,7 @@ export class AgentDocumentModel {
policyLoad?: PolicyLoad;
},
): Promise<void> {
- const { content, editorData, loadPosition, loadRules, metadata, policy, policyLoad } =
+ const { content, editorData, fileType, loadPosition, loadRules, metadata, policy, policyLoad } =
params ?? {};
const existing = await this.findById(documentId);
@@ -608,7 +609,12 @@ export class AgentDocumentModel {
};
await this.db.transaction(async (trx) => {
- if (content !== undefined || editorData !== undefined || metadata !== undefined) {
+ if (
+ content !== undefined ||
+ editorData !== undefined ||
+ fileType !== undefined ||
+ metadata !== undefined
+ ) {
const documentUpdate: Partial<NewDocument> = {};
if (content !== undefined) {
@@ -630,6 +636,10 @@ export class AgentDocumentModel {
documentUpdate.editorData = editorData;
}
+ if (fileType !== undefined) {
+ documentUpdate.fileType = fileType;
+ }
+
if (metadata !== undefined) {
documentUpdate.metadata = metadata;
documentUpdate.description = this.getMetadataDescription(metadata);