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-documents): keep empty-parse shell documents readable and removable (#21027)

Arvin Xud090220c1189
diff --git a/apps/server/src/services/agentDocuments/emptyParseShell.ts b/apps/server/src/services/agentDocuments/emptyParseShell.ts
new file mode 100644
index 00000000000..bbd38417598
--- /dev/null
+++ b/apps/server/src/services/agentDocuments/emptyParseShell.ts
@@ -0,0 +1,50 @@
+import { isEmptyParseShell } from '@/database/models/agentDocuments';
+
+/**
+ * An "empty-parse shell" (childless-root editorData minted before #20914) cannot
+ * hydrate: Lexical rejects the empty editor state with error #38, so every
+ * editorData load re-throws it. Reads and the remove/rename pre-reads therefore
+ * expose the static empty document instead of re-entering the editor; a later
+ * modifyNodes on those ids still reports its precise "did not change the
+ * document" error.
+ *
+ * 2026-10-16 recurrence: msg_XrvhP2q8ZReSgaeQp9 β€” nine pre-#20914 stubs threw
+ * #38 on removeDocument/replaceDocumentContent and could not be cleaned up.
+ */
+export const projectEmptyParseShell = <T extends { content: string | null }>(
+ doc: T,
+): T & { content: string } => ({ ...doc, content: doc.content ?? '' });
+
+export { isEmptyParseShell as isEmptyParseShellDocument };
+
+export const EMPTY_PARSE_SHELL_LITEXML =
+ '<?xml version="1.0" encoding="UTF-8"?>\n<root>\n <p id="42">\n </p>\n</root>';
+
+export const attachEmptyParseShellLiteXML = <T extends { content: string | null }>(
+ doc: T,
+): T & { content: string; editorData: Record<string, unknown>; litexml: string } => ({
+ ...doc,
+ content: doc.content ?? '',
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [],
+ direction: null,
+ format: '',
+ indent: 0,
+ textFormat: 0,
+ textStyle: '',
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+ },
+ litexml: EMPTY_PARSE_SHELL_LITEXML,
+});
diff --git a/apps/server/src/services/agentDocuments/index.emptyParseShell.test.ts b/apps/server/src/services/agentDocuments/index.emptyParseShell.test.ts
new file mode 100644
index 00000000000..58fb30f2e76
--- /dev/null
+++ b/apps/server/src/services/agentDocuments/index.emptyParseShell.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database';
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
+
+import { AgentDocumentsService } from './index';
+
+vi.mock('@/database/models/agentDocuments', async (importOriginal) => ({
+ // Spread the real module so pure helpers (e.g. isEmptyParseShell) keep their
+ // production behavior while the model classes stay mocked.
+ ...(await importOriginal<any>()),
+ AgentDocumentModel: vi.fn(),
+ DocumentLoadPosition: {
+ BEFORE_FIRST_USER: 'before_first_user',
+ },
+ buildDocumentFilename: vi.fn(),
+ deriveAgentDocumentFields: vi.fn(() => ({})),
+}));
+
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/agentSkill', () => ({ AgentSkillModel: vi.fn() }));
+vi.mock('@/database/models/topicDocument', () => ({ TopicDocumentModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('../document', () => ({ DocumentService: vi.fn() }));
+vi.mock('../file', () => ({ FileService: vi.fn() }));
+vi.mock('../skill/resource', () => ({ SkillResourceService: vi.fn() }));
+vi.mock('../agentDocumentVfs', () => ({ AgentDocumentVfsService: vi.fn() }));
+
+const SHELL_DOC_ID = '11111111-1111-4111-8111-111111111111';
+const DOC_ROW_ID = 'ae743612-eef4-4c46-879f-9db9c346e760';
+
+const buildModelStub = () => {
+ const stub: Record<string, any> = {
+ countChildrenByParentIds: vi.fn().mockResolvedValue(new Map()),
+ delete: vi.fn(),
+ deleteSubtreeByDocumentId: vi.fn(),
+ findById: vi.fn(),
+ findByDocumentId: vi.fn(),
+ updateEditorSnapshotIfUnchanged: vi.fn().mockResolvedValue(true),
+ };
+ (AgentDocumentModel as any).mockImplementation(function (this: any) {
+ Object.assign(this, stub);
+ });
+ return stub;
+};
+
+describe('AgentDocumentsService empty-parse shell tolerance', () => {
+ const db = {} as LobeChatDatabase;
+ const userId = 'user-1';
+ let mockModel: Record<string, any>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockModel = buildModelStub();
+ });
+
+ it('getDocumentSnapshotById exposes a shell as the empty document without re-entering the editor', async () => {
+ mockModel.findById = vi.fn().mockResolvedValue({
+ agentId: 'agent-1',
+ content: '',
+ documentId: 'documents-1',
+ // Pre-#20914 shell: childless root editorData + empty content. Hydrating
+ // this state throws Lexical error #38 and used to make the document
+ // unreadable and unremovable (2026-10-16 recurrence).
+ editorData: { root: { children: [], type: 'root' } },
+ id: SHELL_DOC_ID,
+ title: 'VERIFIED-CLONE stub',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.getDocumentSnapshotById(SHELL_DOC_ID, 'agent-1');
+
+ expect(result?.content).toBe('');
+ expect(result?.litexml).toContain('<root');
+ expect(mockModel.updateEditorSnapshotIfUnchanged).not.toHaveBeenCalled();
+ });
+
+ it('removeDocumentById deletes a shell leaf without re-entering the editor', async () => {
+ // 2026-10-16 recurrence: pre-#20914 shells threw Lexical error #38 during
+ // the remove pre-read and nothing was deleted (attempts=12).
+ mockModel.findById = vi.fn().mockResolvedValue({
+ agentId: 'agent-1',
+ content: '',
+ documentId: 'docs_sop',
+ editorData: { root: { children: [], type: 'root' } },
+ fileType: 'agent/document',
+ id: DOC_ROW_ID,
+ title: 'VERIFIED-CLONE stub',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+
+ await expect(service.removeDocumentById(DOC_ROW_ID, 'agent-1')).resolves.toBe(true);
+ expect(mockModel.delete).toHaveBeenCalledWith(DOC_ROW_ID);
+ });
+});
diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.ts
index 0b4a785aec1..48fd7cda352 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -36,6 +36,11 @@ import { DocumentService } from '../document';
import { FileService } from '../file';
import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';
import { isRawTextAgentDocument } from './contentFormat';
+import {
+ attachEmptyParseShellLiteXML,
+ isEmptyParseShellDocument,
+ projectEmptyParseShell,
+} from './emptyParseShell';
import {
type AgentDocumentLiteXMLOperation,
applyLiteXMLOperations,
@@ -228,6 +233,10 @@ export class AgentDocumentsService {
if (!doc?.editorData) return doc;
if (doc.fileType === DOCUMENT_FOLDER_TYPE) return doc;
if (isManagedSkillDocument(doc)) return doc;
+ // An empty-parse shell hydrates to an empty Lexical state, which throws
+ // Lexical error #38 on every editorData load. Project it as the empty
+ // document it is instead of re-entering the editor.
+ if (isEmptyParseShellDocument(doc)) return projectEmptyParseShell(doc);
try {
const snapshot = await exportEditorDataSnapshot({
@@ -264,6 +273,12 @@ export class AgentDocumentsService {
): Promise<AgentDocumentWithLiteXML> {
if (isRawTextAgentDocument(doc)) return doc;
+ // Empty-parse shells cannot hydrate (Lexical error #38). Expose the static
+ // empty LiteXML document instead of re-entering the editor, so reads and
+ // the remove/rename pre-reads stay addressable; a later modifyNodes on
+ // these ids still reports a precise "did not change the document" error.
+ if (isEmptyParseShellDocument(doc)) return attachEmptyParseShellLiteXML(doc);
+
const snapshot = await exportEditorDataSnapshot({
editorData: doc.editorData,
fallbackContent: doc.content,
diff --git a/packages/database/src/models/agentDocuments/copyDocument.ts b/packages/database/src/models/agentDocuments/copyDocument.ts
index 65b7122f456..030a9bdf9bf 100644
--- a/packages/database/src/models/agentDocuments/copyDocument.ts
+++ b/packages/database/src/models/agentDocuments/copyDocument.ts
@@ -18,7 +18,10 @@ const RAW_TEXT_DOCUMENT_FILE_TYPE = 'text/plain';
* 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 => {
+export const isEmptyParseShell = (doc: {
+ content: string | null;
+ editorData: Record<string, any> | null;
+}): boolean => {
const hasRootChildren =
Array.isArray(doc.editorData?.root?.children) &&
(doc.editorData!.root.children.length ?? 0) > 0;
diff --git a/packages/database/src/models/agentDocuments/index.ts b/packages/database/src/models/agentDocuments/index.ts
index ae3b9b41cee..8fe8e9a3744 100644
--- a/packages/database/src/models/agentDocuments/index.ts
+++ b/packages/database/src/models/agentDocuments/index.ts
@@ -1,4 +1,5 @@
export * from './agentDocument';
+export * from './copyDocument';
export * from './deriveFields';
export * from './filename';
export * from './policy';
diff --git a/src/features/EditorCanvas/EditorDataMode.test.tsx b/src/features/EditorCanvas/EditorDataMode.test.tsx
new file mode 100644
index 00000000000..e99827b3899
--- /dev/null
+++ b/src/features/EditorCanvas/EditorDataMode.test.tsx
@@ -0,0 +1,88 @@
+import type { IEditor } from '@lobehub/editor';
+import { render } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+// InternalEditor is the mounting surface; stub it out so the component tree
+// stays free of the real Lexical mount while loadEditorContent still runs for
+// real through handleInit -> loadContentWithLock.
+const internalEditorSpy = vi.hoisted(() => ({
+ onInit: null as null | ((editor: IEditor) => void),
+}));
+
+vi.mock('./InternalEditor', () => ({
+ default: (props: { onInit: (editor: IEditor) => void }) => {
+ internalEditorSpy.onInit = props.onInit;
+ return null;
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('EditorDataMode.loadEditorContent empty-parse shell tolerance', () => {
+ it('routes a childless-root Lexical shell to the fallback instead of json hydration', async () => {
+ vi.resetModules();
+ const { EMPTY_EDITOR_STATE } = await import('@/libs/editor/constants');
+ const mod = await import('./EditorDataMode');
+ const mockEditor = { setDocument: vi.fn() } as unknown as IEditor;
+ const baseProps = {
+ editor: mockEditor,
+ editorData: { content: '', editorData: undefined },
+ onContentChange: vi.fn(),
+ onInit: vi.fn(),
+ } as any;
+
+ const setDocumentSpy = vi.mocked(mockEditor.setDocument);
+ setDocumentSpy.mockClear();
+ internalEditorSpy.onInit = null;
+ const { default: Component } = mod;
+ render(
+ <Component
+ {...baseProps}
+ editorData={{ content: '', editorData: { root: { children: [], type: 'root' } } } as any}
+ />,
+ );
+
+ expect(internalEditorSpy.onInit).toBeTypeOf('function');
+ // The component only loads when InternalEditor reports init; our stub
+ // captured handleInit β€” invoke it the way InternalEditor would.
+ internalEditorSpy.onInit?.(mockEditor);
+
+ expect(setDocumentSpy).not.toHaveBeenCalledWith(
+ 'json',
+ JSON.stringify({ root: { children: [], type: 'root' } }),
+ );
+ expect(setDocumentSpy).toHaveBeenCalledWith('json', JSON.stringify(EMPTY_EDITOR_STATE));
+ });
+
+ it('still loads a legacy non-Lexical payload via setDocument json', async () => {
+ vi.resetModules();
+ const mod = await import('./EditorDataMode');
+ const mockEditor = { setDocument: vi.fn() } as unknown as IEditor;
+ const baseProps = {
+ editor: mockEditor,
+ editorData: { content: '', editorData: undefined },
+ onContentChange: vi.fn(),
+ onInit: vi.fn(),
+ } as any;
+
+ const setDocumentSpy = vi.mocked(mockEditor.setDocument);
+ setDocumentSpy.mockClear();
+ internalEditorSpy.onInit = null;
+ const { default: Component } = mod;
+ render(
+ <Component
+ {...baseProps}
+ editorData={{ content: '', editorData: { type: 'doc', content: [] } } as any}
+ />,
+ );
+
+ internalEditorSpy.onInit?.(mockEditor);
+
+ expect(setDocumentSpy).toHaveBeenCalledWith(
+ 'json',
+ JSON.stringify({ type: 'doc', content: [] }),
+ );
+ });
+});
diff --git a/src/features/EditorCanvas/EditorDataMode.tsx b/src/features/EditorCanvas/EditorDataMode.tsx
index f54d8ea0720..2c909621d85 100644
--- a/src/features/EditorCanvas/EditorDataMode.tsx
+++ b/src/features/EditorCanvas/EditorDataMode.tsx
@@ -19,10 +19,22 @@ const loadEditorContent = (
editorInstance: IEditor,
editorData: EditorDataModeProps['editorData'],
): boolean => {
+ const editorDataRoot = (editorData.editorData as { root?: { children?: unknown[] } } | null)
+ ?.root;
+ // A childless root (empty-parse shell) throws Lexical error #38 on hydration;
+ // treat it as no editor data so the content fallbacks take over. Only the
+ // targeted Lexical shell shape (root node present with an empty children
+ // array) is rejected β€” legacy non-Lexical payloads without a root node
+ // (e.g. { type: 'doc', content: [] }) keep loading via setDocument('json').
+ const isEmptyParseShell =
+ !!editorDataRoot &&
+ Array.isArray(editorDataRoot.children) &&
+ editorDataRoot.children.length === 0;
const hasValidEditorData =
editorData.editorData &&
typeof editorData.editorData === 'object' &&
- Object.keys(editorData.editorData as object).length > 0;
+ Object.keys(editorData.editorData as object).length > 0 &&
+ !isEmptyParseShell;
try {
if (hasValidEditorData) {
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index 556abf0092e..779e60384bd 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -251,10 +251,21 @@ export class EditorActionImpl {
if (!doc) return;
// Check if editorData is valid and non-empty
+ const editorDataRoot = (doc.editorData as { root?: { children?: unknown[] } } | null)?.root;
+ // A childless root (empty-parse shell) throws Lexical error #38 on hydration;
+ // treat it as no editor data so the markdown/empty fallbacks below take over.
+ // Only the targeted Lexical shell shape (root node present with an empty
+ // children array) is rejected β€” legacy non-Lexical payloads without a root
+ // node (e.g. { type: 'doc', content: [] }) keep loading via setDocument('json').
+ const isEmptyParseShell =
+ !!editorDataRoot &&
+ Array.isArray(editorDataRoot.children) &&
+ editorDataRoot.children.length === 0;
const hasValidEditorData =
doc.editorData &&
typeof doc.editorData === 'object' &&
- Object.keys(doc.editorData).length > 0;
+ Object.keys(doc.editorData).length > 0 &&
+ !isEmptyParseShell;
// SKILL.md frontmatter is metadata, not editable document body. Keep it out of the rich
// Markdown editor because `---` fences are otherwise parsed as Markdown dividers/headings,
diff --git a/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts
new file mode 100644
index 00000000000..ab27a1b28bb
--- /dev/null
+++ b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts
@@ -0,0 +1,80 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useDocumentStore } from '../../store';
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),
+ releaseDocumentLock: vi.fn().mockResolvedValue(undefined),
+ getDocumentById: vi.fn().mockResolvedValue(null),
+ updateDocument: vi.fn().mockResolvedValue({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ }),
+ },
+}));
+
+vi.mock('@/services/notebook', () => ({
+ notebookService: { updateDocument: vi.fn().mockResolvedValue({}) },
+}));
+
+const createMockEditor = () => ({
+ getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : null)),
+ setDocument: vi.fn(),
+});
+
+describe('onEditorInit empty-parse shell tolerance (Lexical error #38)', () => {
+ it('treats a childless-root Lexical shell as no editor data and routes to the markdown fallback', () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const mockEditor = createMockEditor() as any;
+
+ act(() => {
+ result.current.initDocumentWithEditor({
+ content: '# Body',
+ documentId: 'doc-1',
+ editor: mockEditor,
+ editorData: { root: { children: [], type: 'root' } },
+ sourceType: 'page',
+ });
+ });
+
+ act(() => {
+ result.current.onEditorInit(mockEditor);
+ });
+
+ // The empty-parse shell must not reach setDocument('json') β€” it would
+ // throw Lexical error #38 on hydration β€” so the markdown fallback runs.
+ expect(mockEditor.setDocument).not.toHaveBeenCalledWith(
+ 'json',
+ JSON.stringify({ root: { children: [], type: 'root' } }),
+ { keepId: true },
+ );
+ expect(mockEditor.setDocument).toHaveBeenCalledWith('markdown', '# Body');
+ });
+
+ it('preserves the legacy non-Lexical payload contract ({ type: doc, content })', () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const mockEditor = createMockEditor() as any;
+ const legacy = { type: 'doc', content: [] };
+
+ act(() => {
+ result.current.initDocumentWithEditor({
+ content: '',
+ documentId: 'doc-legacy',
+ editor: mockEditor,
+ editorData: legacy,
+ sourceType: 'page',
+ });
+ });
+
+ act(() => {
+ result.current.onEditorInit(mockEditor);
+ });
+
+ expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(legacy), {
+ keepId: true,
+ });
+ });
+});