π€― 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(agent-documents): stop minting and cloning empty-parse document shells (#20914)
Arvin Xuc6669b062fe5
diff --git a/apps/server/src/routers/lambda/webBrowsing.ts b/apps/server/src/routers/lambda/webBrowsing.tsindex 62c4b956eb6..a0e407b2c29 100644--- a/apps/server/src/routers/lambda/webBrowsing.ts+++ b/apps/server/src/routers/lambda/webBrowsing.ts@@ -33,6 +33,8 @@ export const webBrowsingRouter = router({.input(z.object({content: z.string(),+ /** Crawler content type; `json` bodies get wrapped in a fenced code block before persisting. */+ contentType: z.literal('json').optional(),description: z.string().optional(),title: z.string(),topicId: z.string().optional(),diff --git a/apps/server/src/services/agentDocumentVfs/index.test.ts b/apps/server/src/services/agentDocumentVfs/index.test.tsindex 0976b2ca1f8..62e5da29d19 100644--- a/apps/server/src/services/agentDocumentVfs/index.test.ts+++ b/apps/server/src/services/agentDocumentVfs/index.test.ts@@ -336,7 +336,7 @@ ${'lossless tool result\n'.repeat(100)}metadata: null,updatedAt: new Date('2024-01-02T00:00:00.000Z'),});- const createSnapshotSpy = vi.spyOn(headlessEditor, 'createMarkdownEditorSnapshot');+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');const service = new AgentDocumentVfsService(db, userId);const node = await service.write('./archive.txt',@@ -372,7 +372,7 @@ ${'lossless tool result\n'.repeat(100)}mockAgentDocumentModel.update.mockImplementation(async (_id, params) => {Object.assign(existing, params);});- const createSnapshotSpy = vi.spyOn(headlessEditor, 'createMarkdownEditorSnapshot');+ const createSnapshotSpy = vi.spyOn(headlessEditor, 'createAgentMarkdownSnapshot');const service = new AgentDocumentVfsService(db, userId);await service.write(diff --git a/apps/server/src/services/agentDocumentVfs/index.ts b/apps/server/src/services/agentDocumentVfs/index.tsindex daa0cb5e3c8..58ffa73ebb6 100644--- a/apps/server/src/services/agentDocumentVfs/index.ts+++ b/apps/server/src/services/agentDocumentVfs/index.ts@@ -13,7 +13,7 @@ import {getAgentDocumentContentType,RAW_TEXT_DOCUMENT_FILE_TYPE,} from '../agentDocuments/contentFormat';-import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';+import { createAgentMarkdownSnapshot } from '../agentDocuments/headlessEditor';import { FileService } from '../file';import { AgentDocumentVfsError } from './errors';import { createSkillMount } from './mounts/skills/createSkillMount';@@ -836,7 +836,7 @@ export class AgentDocumentVfsService {fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,});} else {- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(content);await this.agentDocumentModel.update(existing.id, {content: snapshot.content,editorData: snapshot.editorData,@@ -897,7 +897,7 @@ export class AgentDocumentVfsService {return this.toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));}- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(content);const created = await this.agentDocumentModel.create(ctx.agentId,normalizedFilename,diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.tsindex 68b64265005..7eec01d035f 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts@@ -299,4 +299,75 @@ describe('agent document headless editor', () => {await expect(createAgentMarkdownSnapshot('{draft} notes')).resolves.toBeDefined();});});++ // T-775: crawl captures (raw HTML/XML pages that Markdown parsing empties)+ // used to persist as empty-parse shells via the unguarded snapshot: content=''+ // + editorData {root:{children:[]}}. The shell then read back as Lexical error+ // #38 ("the editor state is empty"), blocked copy/remove cleanup, and cloned+ // itself through copyDocument. The guarded agent snapshot must reject those+ // bodies instead of minting another shell.+ describe('empty-parse bodies (crawl captures)', () => {+ const htmlBody =+ '<!DOCTYPE html><html><head><title>Page</title></head><body>' ++ '<div class="row"><span>cell</span></div>'.repeat(500) ++ '</body></html>';++ const xmlBody =+ '<?xml version="1.0" encoding="UTF-8"?>\n<results>' ++ Array.from(+ { length: 200 },+ (_, i) =>+ `<result><title>T${i}</title><content>Body text ${i} with some length to it.</content><url>https://example.com/${i}</url></result>`,+ ).join('') ++ '</results>';++ it('rejects a raw HTML crawl body that parses to nothing', async () => {+ // Unguarded snapshot silently mints the shell:+ const unguarded = await createMarkdownEditorSnapshot(htmlBody);+ expect(unguarded.content).toBe('');+ expect(isValidEditorData(unguarded.editorData)).toBe(false);++ await expect(createAgentMarkdownSnapshot(htmlBody)).rejects.toThrow(+ /empty document after Markdown parsing/i,+ );+ });++ it('rejects a raw XML crawl body that parses to nothing', async () => {+ const unguarded = await createMarkdownEditorSnapshot(xmlBody);+ expect(unguarded.content).toBe('');++ // `<?xml β¦` hits the LiteXML guard before the empty-parse guard; either+ // way the body is rejected and nothing is persisted.+ await expect(createAgentMarkdownSnapshot(xmlBody)).rejects.toThrow(+ /looks like LiteXML|empty document after Markdown parsing/i,+ );+ });++ it('rejects an XML document fragment body that parses to nothing', async () => {+ // A comment-only XML fragment carries no Markdown-renderable text β the+ // empty-parse guard's case.+ const fragment =+ '<results>' ++ Array.from({ length: 200 }, (_, i) => `<!-- result row ${i} -->`).join('') ++ '</results>';++ const unguarded = await createMarkdownEditorSnapshot(fragment);+ expect(unguarded.content).toBe('');++ await expect(createAgentMarkdownSnapshot(fragment)).rejects.toThrow(+ /empty document after Markdown parsing/i,+ );+ });++ it('still accepts real Markdown bodies of any length', async () => {+ const markdown = Array.from(+ { length: 300 },+ (_, i) => `## Section ${i}\n\nParagraph ${i} with content.\n`,+ ).join('\n');++ const snapshot = await createAgentMarkdownSnapshot(markdown);+ expect(snapshot.content).toContain('Section 0');+ expect(isValidEditorData(snapshot.editorData)).toBe(true);+ });+ });});diff --git a/apps/server/src/services/webBrowsing/__tests__/index.test.ts b/apps/server/src/services/webBrowsing/__tests__/index.test.tsindex f4bd8fc8af6..c53ac64ad82 100644--- a/apps/server/src/services/webBrowsing/__tests__/index.test.ts+++ b/apps/server/src/services/webBrowsing/__tests__/index.test.ts@@ -34,7 +34,7 @@ vi.mock('@/server/services/document', () => ({}));vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({- createMarkdownEditorSnapshot: vi.fn(async (content: string) => ({+ createAgentMarkdownSnapshot: vi.fn(async (content: string) => ({content,editorData: { root: { fakeNodeFor: content } },})),@@ -244,4 +244,83 @@ describe('WebBrowsingDocumentService.upsertCrawledDocument ()', () => {expect(mocks.documentService.updateDocument).toHaveBeenCalled();expect(result).toEqual({ id: 'doc-legacy', status: 'updated' });});++ // T-775: upsertCrawledDocument routes through the guarded agent snapshot, so+ // a body Markdown parsing empties (raw HTML/XML crawl pages) rejects the save+ // instead of persisting an empty-parse shell (content='' + childless root+ // editorData) that later reads as Lexical error #38 and blocks cleanup.+ // The guard's own parsing behavior is covered by headlessEditor tests; here we+ // verify the service wiring propagates the rejection without touching storage.+ it('routes create through the guarded agent markdown snapshot and propagates its rejection', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ const { createAgentMarkdownSnapshot } =+ await import('@/server/services/agentDocuments/headlessEditor');+ vi.mocked(createAgentMarkdownSnapshot).mockRejectedValueOnce(+ new Error(+ 'Document content produced an empty document after Markdown parsing; nothing was saved. Send the document body as Markdown.',+ ),+ );++ await expect(+ service.upsertCrawledDocument({+ content: '<html><body>shell-prone body</body></html>',+ title: 'Shell page',+ url: 'https://example.com/shell',+ }),+ ).rejects.toThrow(/empty document after Markdown parsing/i);++ expect(createAgentMarkdownSnapshot).toHaveBeenCalledWith(+ '<html><body>shell-prone body</body></html>',+ );+ expect(mocks.documentModel.create).not.toHaveBeenCalled();+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();+ });++ // Codex P1 on #20914: the naive crawler returns raw JSON for+ // `application/json` responses (a supported crawl), but the guarded agent+ // snapshot rejects raw JSON. The persistence boundary must wrap JSON bodies+ // in a fenced code block β fenced code is stored byte-exact, so the JSON+ // stays parseable and the guard's own fence handling covers it.+ it('wraps a json crawl body in a fenced code block before the snapshot guard', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-json' });++ const raw = '{"url":"https://example.com/data","items":[1,2],"nested":{"a":"b"}}';++ const result = await service.upsertCrawledDocument({+ content: raw,+ contentType: 'json',+ title: 'JSON endpoint',+ url: 'https://example.com/data.json',+ });++ const expected = '```json\n' + raw + '\n```';+ expect(mocks.documentModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ content: expected,+ editorData: { root: { fakeNodeFor: expected } },+ }),+ );+ expect(result).toEqual({ id: 'doc-json', status: 'created' });+ });++ it('hashes the fenced json body so an unchanged json re-crawl short-circuits', async () => {+ const raw = '{"same":true}';+ const fenced = '```json\n' + raw + '\n```';+ mocks.documentModel.findBySource.mockResolvedValueOnce({+ content: fenced,+ id: 'doc-json',+ } as any);++ const result = await service.upsertCrawledDocument({+ content: raw,+ contentType: 'json',+ title: 'JSON endpoint',+ url: 'https://example.com/data.json',+ });++ expect(result).toEqual({ id: 'doc-json', status: 'unchanged' });+ expect(mocks.documentModel.create).not.toHaveBeenCalled();+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/services/webBrowsing/index.ts b/apps/server/src/services/webBrowsing/index.tsindex 93bf9845580..64c6f235737 100644--- a/apps/server/src/services/webBrowsing/index.ts+++ b/apps/server/src/services/webBrowsing/index.ts@@ -3,11 +3,18 @@ import { Md5 } from 'ts-md5';import { DocumentModel } from '@/database/models/document';import { TopicDocumentModel } from '@/database/models/topicDocument';-import { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';+import { createAgentMarkdownSnapshot } from '@/server/services/agentDocuments/headlessEditor';import { DocumentService } from '@/server/services/document';export interface UpsertCrawledDocumentParams {content: string;+ /**+ * Crawler content type from `CrawlSuccessResult`. A `json` body is wrapped+ * in a fenced code block before persisting: the agent markdown snapshot+ * guard rejects raw JSON (markdown parsing would rewrite escapes and+ * emphasis), while fenced code blocks are stored byte-exact.+ */+ contentType?: 'json';description?: string;title: string;/**@@ -33,6 +40,14 @@ export interface UpsertCrawledDocumentResult {const hashContent = (content: string): string => Md5.hashStr(content);+/**+ * Wrap a raw JSON crawl body in a fenced code block so it survives the agent+ * markdown snapshot guard: raw JSON is rejected (markdown parsing would drop+ * backslash escapes and pair `__`/`*` into emphasis), while fenced code+ * blocks are stored byte-exact and keep the JSON parseable.+ */+const wrapJsonCrawlContent = (content: string): string => `\`\`\`json\n${content.trim()}\n\`\`\``;+/*** Single owner of "crawl a web page, persist it as a document" semantics.*@@ -84,7 +99,11 @@ export class WebBrowsingDocumentService {upsertCrawledDocument = async (params: UpsertCrawledDocumentParams,): Promise<UpsertCrawledDocumentResult> => {- const { content, description, title, topicId, url } = params;+ const { content, contentType, description, title, topicId, url } = params;++ // Raw JSON bodies must be fenced before hitting the markdown snapshot+ // guard (see `UpsertCrawledDocumentParams.contentType`).+ const persistedContent = contentType === 'json' ? wrapJsonCrawlContent(content) : content;const existing = await this.documentModel.findBySource(url, 'web');@@ -92,14 +111,14 @@ export class WebBrowsingDocumentService {let status: UpsertCrawledDocumentResult['status'];if (existing) {- if (hashContent(existing.content ?? '') === hashContent(content)) {+ if (hashContent(existing.content ?? '') === hashContent(persistedContent)) {// Byte-identical content β skip the write entirely. Both `documents`// and `document_histories` would only churn `updated_at`, which is// not worth the cost (and pollutes the history list with no-op rows).documentId = existing.id;status = 'unchanged';} else {- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(persistedContent);// `DocumentService.updateDocument` runs inside a transaction and// writes a `document_histories` row when `editorData` differs from// the row's current snapshot, so each refresh becomes a revision.@@ -113,7 +132,7 @@ export class WebBrowsingDocumentService {status = 'updated';}} else {- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(persistedContent);const created = await this.documentModel.create({content: snapshot.content,description,diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.tsindex a5d3085d5eb..40a6ade5e7b 100644--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts@@ -17,6 +17,13 @@ export interface WebBrowsingDocumentService {associateDocument: (documentId: string) => Promise<{ id?: string } | void>;createDocument: (params: {content: string;+ /**+ * Crawler content type from `CrawlSuccessResult`. The persistence layer+ * wraps `json` bodies in a fenced code block β the markdown snapshot+ * guard rejects raw JSON (markdown parsing would rewrite it), but fenced+ * blocks are stored byte-exact.+ */+ contentType?: 'json';description?: string;title: string;url: string;@@ -114,6 +121,7 @@ export class WebBrowsingExecutionRuntime {try {const doc = await this.documentService!.createDocument({content: pageData.content,+ ...(pageData.contentType === 'json' && { contentType: 'json' }),description: pageData.description || `Crawled from ${pageData.url}`,title: pageData.title || pageData.url,url: pageData.url,diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.copy.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.copy.test.tsnew file mode 100644index 00000000000..b2895d7bbf5--- /dev/null+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.copy.test.ts@@ -0,0 +1,83 @@+// @vitest-environment node+// Focused copy-scenario tests for `AgentDocumentModel.copy` β extracted from+// the oversized `agentDocument.test.ts` per the source-layout 800-line rule+// (Codex P2 on #20914). Copy parameter assembly itself lives in+// `../copyDocument.ts`.+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { AgentDocumentModel, DocumentLoadPosition, PolicyLoad } from '../agentDocument';++const userId = 'agent-document-copy-test-user';+const agentId = 'agent-document-copy-test-agent';++let agentDocumentModel: AgentDocumentModel;+const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ await serverDB.delete(users);++ await serverDB.insert(users).values([{ id: userId }]);+ await serverDB.insert(agents).values([{ id: agentId, userId }]);++ agentDocumentModel = new AgentDocumentModel(serverDB, userId);+});++describe('AgentDocumentModel.copy', () => {+ it('should copy into a new record and keep policy/template metadata', async () => {+ const created = await agentDocumentModel.create(agentId, 'copy-source.md', 'copy me', {+ loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,+ loadRules: { maxTokens: 200, priority: 3 },+ metadata: { description: 'source desc', domain: 'A' },+ templateId: 'claw',+ });++ const copied = await agentDocumentModel.copy(created.id, 'Copied Title');++ expect(copied).toBeDefined();+ expect(copied?.id).not.toBe(created.id);+ expect(copied?.documentId).not.toBe(created.documentId);+ expect(copied?.filename).toBe('Copied Title');+ expect(copied?.templateId).toBe('claw');+ expect(copied?.policy?.context?.maxTokens).toBe(200);+ expect(copied?.metadata).toMatchObject({ description: 'source desc', domain: 'A' });+ });++ it('should preserve policyLoad when copying a document', async () => {+ const created = await agentDocumentModel.create(agentId, 'always-doc.md', 'content', {+ policyLoad: PolicyLoad.ALWAYS,+ });++ const copied = await agentDocumentModel.copy(created.id, 'Always Copy');++ expect(copied?.policyLoad).toBe(PolicyLoad.ALWAYS);+ });++ // T-775: an empty-parse shell (editorData with a childless root and empty+ // content β what a raw HTML/XML crawl capture used to persist) must not be+ // duplicated as another shell. The clone reads as Lexical error #38 and+ // blocks cleanup, so copy stores it as raw text instead.+ it('should not duplicate an empty-parse shell as editor data when copying', async () => {+ const created = await agentDocumentModel.create(agentId, 'shell-source.md', '', {+ editorData: {+ root: {+ children: [],+ direction: 'ltr',+ format: '',+ indent: 0,+ type: 'root',+ version: 1,+ },+ } as any,+ });+ expect(created.content).toBe('');++ const copied = await agentDocumentModel.copy(created.id, 'Shell Copy');++ expect(copied).toBeDefined();+ expect(copied?.fileType).toBe('text/plain');+ expect(copied?.editorData ?? null).toBeNull();+ });+});diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex 61968ace5ff..0979f6a6be8 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -788,25 +788,6 @@ describe('AgentDocumentModel', () => {]);});- it('should copy into a new record and keep policy/template metadata', async () => {- const created = await agentDocumentModel.create(agentId, 'copy-source.md', 'copy me', {- loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,- loadRules: { maxTokens: 200, priority: 3 },- metadata: { description: 'source desc', domain: 'A' },- templateId: 'claw',- });-- const copied = await agentDocumentModel.copy(created.id, 'Copied Title');-- expect(copied).toBeDefined();- expect(copied?.id).not.toBe(created.id);- expect(copied?.documentId).not.toBe(created.documentId);- expect(copied?.filename).toBe('Copied Title');- expect(copied?.templateId).toBe('claw');- expect(copied?.policy?.context?.maxTokens).toBe(200);- expect(copied?.metadata).toMatchObject({ description: 'source desc', domain: 'A' });- });-it('should preserve policyLoad when copying a document', async () => {const created = await agentDocumentModel.create(agentId, 'always-doc.md', 'content', {policyLoad: PolicyLoad.ALWAYS,@@ -816,6 +797,10 @@ describe('AgentDocumentModel', () => {expect(copied?.policyLoad).toBe(PolicyLoad.ALWAYS);});++ // Copy scenarios (incl. the T-775 empty-parse-shell regression) moved to+ // the focused `agentDocument.copy.test.ts` per the source-layout 800-line+ // rule (Codex P2 on #20914).});describe('convertAgentDocumentToSkillIndex and updateDocumentIdentity', () => {diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex eb080541846..f8c95d2e1e2 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -22,6 +22,7 @@ import { AGENT_SKILL_TEMPLATE_ID, agentDocuments, documents } from '../../schemaimport type { LobeChatDatabase, Transaction } from '../../type';import { documentMatchesAccessScope } from '../../utils/documentVisibility';import { buildWorkspaceWhere } from '../../utils/workspace';+import { buildCopyParams } from './copyDocument';import { deriveAgentDocumentFields } from './deriveFields';import { buildDocumentFilename } from './filename';import {@@ -983,18 +984,15 @@ export class AgentDocumentModel {? buildDocumentFilename(title): `copy-${Date.now()}-${existing.filename}`;- return this.create(existing.agentId, filename, existing.content, {- editorData: existing.editorData || undefined,- title,- loadPosition:- (existing.policy?.context?.position as DocumentLoadPosition | undefined) ||- DocumentLoadPosition.BEFORE_FIRST_USER,- loadRules: parseLoadRules(existing),- metadata: existing.metadata || undefined,- policy: existing.policy || undefined,- policyLoad: existing.policyLoad as PolicyLoad | undefined,- templateId: existing.templateId || undefined,- });+ // Empty-parse shells must not be duplicated as another shell (the clone+ // reads as Lexical error #38 and blocks cleanup); see `copyDocument.ts`+ // for the shell detection and raw-text downgrade.+ return this.create(+ existing.agentId,+ filename,+ existing.content,+ buildCopyParams(existing, title),+ );}async updateToolLoadRule(diff --git a/packages/database/src/models/agentDocuments/copyDocument.ts b/packages/database/src/models/agentDocuments/copyDocument.tsnew file mode 100644index 00000000000..65b7122f456--- /dev/null+++ b/packages/database/src/models/agentDocuments/copyDocument.ts@@ -0,0 +1,55 @@+import { parseLoadRules } from './policy';+import type { AgentDocument, PolicyLoad } from './types';+import { DocumentLoadPosition } from './types';++/**+ * Cohesive "copy an agent document" parameter assembly, extracted from+ * `agentDocument.ts` to keep that file from growing past the repository's+ * 800-line source-layout limit (Codex P2 on #20914).+ */++/** `'text/plain'` = RAW_TEXT_DOCUMENT_FILE_TYPE (apps/server contentFormat); kept literal because the database package cannot import from apps. */+const RAW_TEXT_DOCUMENT_FILE_TYPE = 'text/plain';++/**+ * An "empty-parse shell" (invalid or childless root editorData with empty+ * content, e.g. a crawl capture whose HTML body parsed to nothing) reads as+ * Lexical error #38 and blocks cleanup. Copying such a source as editor data+ * would duplicate the shell, so the clone is stored as raw text instead β the+ * description/metadata survive and the clone is deletable/editable.+ */+export const isEmptyParseShell = (doc: AgentDocument): boolean => {+ const hasRootChildren =+ Array.isArray(doc.editorData?.root?.children) &&+ (doc.editorData!.root.children.length ?? 0) > 0;+ return Boolean(doc.editorData) && !hasRootChildren && !doc.content;+};++const sharedCopyParams = (existing: AgentDocument, title?: string) => ({+ loadPosition:+ (existing.policy?.context?.position as DocumentLoadPosition | undefined) ||+ DocumentLoadPosition.BEFORE_FIRST_USER,+ loadRules: parseLoadRules(existing),+ metadata: existing.metadata || undefined,+ policy: existing.policy || undefined,+ policyLoad: existing.policyLoad as PolicyLoad | undefined,+ templateId: existing.templateId || undefined,+ title,+});++/**+ * Build the `create` params for cloning `existing`. Empty-parse shells are+ * downgraded to raw text (no editor data); everything else clones editorData.+ */+export const buildCopyParams = (existing: AgentDocument, title?: string) =>+ isEmptyParseShell(existing)+ ? {+ ...sharedCopyParams(existing, title),+ // Raw text keeps the clone readable and deletable instead of another+ // error-#38 shell.+ fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,+ }+ : {+ ...sharedCopyParams(existing, title),+ editorData: existing.editorData || undefined,+ };diff --git a/src/services/webBrowsing.ts b/src/services/webBrowsing.tsindex 84ad927eced..b1e934e5684 100644--- a/src/services/webBrowsing.ts+++ b/src/services/webBrowsing.ts@@ -2,6 +2,8 @@ import { lambdaClient } from '@/libs/trpc/client';interface UpsertCrawledDocumentParams {content: string;+ /** Crawler content type; `json` bodies get wrapped in a fenced code block before persisting. */+ contentType?: 'json';description?: string;title: string;topicId?: string;diff --git a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts b/src/store/tool/slices/builtin/executors/lobe-web-browsing.tsindex 8bf6c09a540..3a9875da9a3 100644--- a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts+++ b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts@@ -27,9 +27,10 @@ const createDocumentService = (ctx: BuiltinToolContext): WebBrowsingDocumentServif (!ctx.agentId) return;return agentDocumentService.associateDocument({ agentId: ctx.agentId, documentId });},- createDocument: async ({ content, description, title, url }) =>+ createDocument: async ({ content, contentType, description, title, url }) =>webBrowsingService.upsertCrawledDocument({content,+ ...(contentType === 'json' && { contentType: 'json' }),description: description || `Crawled from ${url}`,title,topicId: ctx.topicId ?? undefined,