🤯 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 modifyNodes and markdown writes from failing silently (#19969)
Arvin Xucef83d6b0cb5
diff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.tsindex 25c847803dc..c71b8302f7a 100644--- a/apps/cli/src/commands/doc.test.ts+++ b/apps/cli/src/commands/doc.test.ts@@ -261,6 +261,10 @@ describe('doc command', () => {title: 'My Doc',}),);+ // The server builds Lexical editor state from content; a `{ type: 'doc' }`+ // placeholder made node ids change on every read.+ const [params] = mockTrpcClient.document.createDocument.mutate.mock.calls[0];+ expect(params).not.toHaveProperty('editorData');expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('new-doc'));});@@ -388,6 +392,8 @@ describe('doc command', () => {expect.objectContaining({ content: 'content2', title: 'Doc 2' }),]),});+ const [{ documents }] = mockTrpcClient.document.createDocuments.mutate.mock.calls[0];+ expect(documents.every((doc: object) => !('editorData' in doc))).toBe(true);expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Created 2'));vi.restoreAllMocks();@@ -463,6 +469,8 @@ describe('doc command', () => {id: 'doc1',}),);+ const [params] = mockTrpcClient.document.updateDocument.mutate.mock.calls[0];+ expect(params).not.toHaveProperty('editorData');});it('should update file type', async () => {diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.tsindex eeedd319c0b..ae07a103efd 100644--- a/apps/cli/src/commands/doc.ts+++ b/apps/cli/src/commands/doc.ts@@ -140,8 +140,8 @@ export function registerDocCommand(program: Command) {const buildUrl = await resolveAppUrlBuilder(client);const result = await client.document.createDocument.mutate({+ // The server builds the editor state from `content`; the CLI has no editor.content,- editorData: JSON.stringify({ content: content || '', type: 'doc' }),fileType: options.fileType,knowledgeBaseId: options.kb,// Inside an agent run, credit the document to that run so it shows up@@ -196,7 +196,6 @@ export function registerDocCommand(program: Command) {const items = documents.map((d) => ({content: d.content,- editorData: JSON.stringify({ content: d.content || '', type: 'doc' }),fileType: d.fileType,knowledgeBaseId: d.knowledgeBaseId,parentId: d.parentId,@@ -255,10 +254,8 @@ export function registerDocCommand(program: Command) {const params: Record<string, any> = { id };if (options.title) params.title = options.title;- if (content !== undefined) {- params.content = content;- params.editorData = JSON.stringify({ content, type: 'doc' });- }+ // The server rebuilds the editor state from the new content.+ if (content !== undefined) params.content = content;if (options.parent !== undefined) {params.parentId = options.parent || null;}diff --git a/apps/cli/src/commands/kb.ts b/apps/cli/src/commands/kb.tsindex 251a477c2f9..57e6a0e02a4 100644--- a/apps/cli/src/commands/kb.ts+++ b/apps/cli/src/commands/kb.ts@@ -291,7 +291,6 @@ export function registerKbCommand(program: Command) {const buildUrl = await resolveAppUrlBuilder(client);const result = await client.document.createDocument.mutate({content: options.content,- editorData: JSON.stringify({}),fileType: 'custom/document',knowledgeBaseId,parentId: options.parent,diff --git a/apps/cli/src/commands/task/doc.ts b/apps/cli/src/commands/task/doc.tsindex 7e398cbf5a4..8d50dd697b4 100644--- a/apps/cli/src/commands/task/doc.ts+++ b/apps/cli/src/commands/task/doc.ts@@ -27,7 +27,6 @@ export function registerDocCommands(task: Command) {const content = options.body || '';const result = await client.document.createDocument.mutate({content,- editorData: options.folder ? undefined : JSON.stringify({ content, type: 'doc' }),fileType,parentId: options.parent,title: options.title,diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.tsindex 201eed3c95a..b18c42f0a8c 100644--- a/apps/server/src/routers/lambda/document.ts+++ b/apps/server/src/routers/lambda/document.ts@@ -18,6 +18,7 @@ import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { DocumentService } from '@/server/services/document';+import { resolveDocumentEditorData } from '@/server/services/document/editorData';import { canViewDocumentContent } from '@/server/services/documentAccess';import { FileService } from '@/server/services/file';import {@@ -225,10 +226,11 @@ export const documentRouter = router({await assertCanCreateUnderParent(ctx, resolvedParentId);- // Parse editorData from JSON string to object- const editorData = documentInput.editorData- ? JSON.parse(documentInput.editorData)- : undefined;+ const editorData = await resolveDocumentEditorData({+ content: documentInput.content,+ editorData: documentInput.editorData ? JSON.parse(documentInput.editorData) : undefined,+ fileType: documentInput.fileType,+ });const document = await ctx.documentService.createDocument({...documentInput,editorData,@@ -258,7 +260,7 @@ export const documentRouter = router({documents: z.array(z.object({content: z.string().optional(),- editorData: z.string(),+ editorData: z.string().optional(),fileType: z.string().optional(),knowledgeBaseId: z.string().optional(),metadata: z.record(z.string(), z.any()).optional(),@@ -283,8 +285,11 @@ export const documentRouter = router({}}- // Parse editorData from JSON string to object- const editorData = JSON.parse(doc.editorData);+ const editorData = await resolveDocumentEditorData({+ content: doc.content,+ editorData: doc.editorData ? JSON.parse(doc.editorData) : undefined,+ fileType: doc.fileType,+ });return {...doc,@@ -566,8 +571,11 @@ export const documentRouter = router({}const { id, editorData: editorDataString, operationId, ...params } = input;- // Parse editorData from JSON string to object if present- const editorData = editorDataString ? JSON.parse(editorDataString) : undefined;+ const editorData = await resolveDocumentEditorData({+ content: params.content,+ editorData: editorDataString ? JSON.parse(editorDataString) : undefined,+ fileType: params.fileType,+ });const result = await ctx.documentService.updateDocument(id, {...params,editorData,diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.tsindex 4a39a8ce6ac..7d7a96fbb0e 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts@@ -159,7 +159,7 @@ describe('agent document headless editor', () => {).rejects.toThrow('unexpectedly produced empty content');});- it('should reject a node edit that silently makes no change', async () => {+ it('should reject a node edit that targets an unknown node id', async () => {const initial = await exportEditorDataSnapshot({fallbackContent: 'Original',litexml: true,@@ -177,6 +177,6 @@ describe('agent document headless editor', () => {},],}),- ).rejects.toThrow('did not change the document');+ ).rejects.toThrow('Operation 1 of 1 (insert) failed: node "missing-node" not found');});});diff --git a/apps/server/src/services/agentDocuments/headlessEditor.ts b/apps/server/src/services/agentDocuments/headlessEditor.tsindex f81c9025956..b0bc1109e99 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.ts@@ -1,3 +1,11 @@+import {+ describeLiteXMLEditStep,+ findLiteXMLEditStepProblem,+ indexLiteXMLDocument,+ normalizeLiteXMLFragment,+ planLiteXMLEditSteps,+ touchesList,+} from '@lobechat/editor-runtime';import type { HeadlessLiteXMLOperation } from '@lobehub/editor/headless';import { createHeadlessEditor } from '@lobehub/editor/headless';import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';@@ -27,30 +35,9 @@ export type AgentDocumentLiteXMLOperation =id: string;};-const orderLiteXMLOperations = (- operations: AgentDocumentLiteXMLOperation[],-): AgentDocumentLiteXMLOperation[] => {- const orderedOperations: AgentDocumentLiteXMLOperation[] = [];-- for (const operation of operations) {- if (operation.action === 'insert') {- orderedOperations.unshift(operation);- } else {- orderedOperations.push(operation);- }- }-- return orderedOperations;-};--const normalizeLiteXMLFragment = (litexml: string) => {- const trimmed = litexml.trim();-- return trimmed.startsWith('<root>') ? trimmed : `<root>${trimmed}</root>`;-};-const toHeadlessLiteXMLOperation = (operation: AgentDocumentLiteXMLOperation,+ delay: boolean,): HeadlessLiteXMLOperation => {switch (operation.action) {case 'insert': {@@ -58,13 +45,13 @@ const toHeadlessLiteXMLOperation = (? {action: 'insert',beforeId: operation.beforeId,- delay: true,+ delay,litexml: normalizeLiteXMLFragment(operation.litexml),}: {action: 'insert',afterId: operation.afterId,- delay: true,+ delay,litexml: normalizeLiteXMLFragment(operation.litexml),};}@@ -72,7 +59,7 @@ const toHeadlessLiteXMLOperation = (case 'modify': {return {action: 'replace',- delay: true,+ delay,litexml: operation.litexml,};}@@ -80,13 +67,16 @@ const toHeadlessLiteXMLOperation = (case 'remove': {return {action: 'remove',- delay: true,+ delay,id: operation.id,};}}};+const NOTHING_SAVED_HINT =+ 'No operations were saved. Call readDocument to get the current node ids, then retry the whole batch.';+export interface AgentDocumentEditorSnapshot {content: string;editorData: AgentDocumentEditorData;@@ -184,7 +174,13 @@ const createEditorWithState = (}hydrateMarkdownOrEmptyState(editor, fallbackContent, { keepId: true });- return { editor, recoveredFromMarkdown: isValidEditorData(editorData) };+ // Node ids minted from Markdown differ on every parse, so any snapshot that+ // exposes them must be persisted — including editorData in a non-Lexical shape+ // (older `lh doc` builds wrote `{ type: 'doc', content }`) or none at all.+ return {+ editor,+ recoveredFromMarkdown: isValidEditorData(editorData) || fallbackContent.trim().length > 0,+ };};export const createMarkdownEditorSnapshot = async (@@ -201,6 +197,33 @@ export const createMarkdownEditorSnapshot = async (}});+const LITEXML_DOCUMENT_PATTERN = /^\s*(?:<\?xml[\s?]|<root[\s>])/;++/**+ * Markdown snapshot for content written by an agent. Rejects input that would+ * silently become an empty document — most often LiteXML sent to a Markdown+ * write API — instead of saving the empty result and reporting success.+ */+export const createAgentMarkdownSnapshot = async (+ content: string,+): Promise<AgentDocumentEditorSnapshot> => {+ if (LITEXML_DOCUMENT_PATTERN.test(content)) {+ throw new Error(+ 'Document content looks like LiteXML, but this API expects Markdown. Send Markdown, or use modifyNodes to edit nodes by id.',+ );+ }++ const snapshot = await createMarkdownEditorSnapshot(content);++ if (content.trim().length > 0 && snapshot.content.trim().length === 0) {+ throw new Error(+ 'Document content produced an empty document after Markdown parsing; nothing was saved. Send the document body as Markdown.',+ );+ }++ return snapshot;+};+export const exportEditorDataSnapshot = async (params: LoadEditorStateParams & { litexml?: boolean },): Promise<AgentDocumentEditorSnapshot> =>@@ -228,21 +251,45 @@ export const applyLiteXMLOperations = async ({try {const beforeSnapshot = exportSnapshot(editor, true);- await editor.applyLiteXML(orderLiteXMLOperations(operations).map(toHeadlessLiteXMLOperation));- const snapshot = exportSnapshot(editor, true);+ let current = beforeSnapshot;++ // Apply in array order, one operation at a time, so every operation is+ // checked on its own: an unknown id or an operation the editor silently+ // drops fails the whole batch instead of being counted as applied.+ for (const step of planLiteXMLEditSteps(+ operations,+ indexLiteXMLDocument(beforeSnapshot.litexml ?? ''),+ )) {+ const { operation } = step;+ const label = describeLiteXMLEditStep(step, operations.length);+ const document = indexLiteXMLDocument(current.litexml ?? '');++ const problem = findLiteXMLEditStepProblem(operation, document);+ if (problem) throw new Error(`${label} failed: ${problem}. ${NOTHING_SAVED_HINT}`);++ await editor.applyLiteXML(+ toHeadlessLiteXMLOperation(operation, !touchesList(operation, document)),+ );+ const next = exportSnapshot(editor, true);++ if (+ next.litexml === current.litexml &&+ JSON.stringify(next.editorData) === JSON.stringify(current.editorData)+ ) {+ throw new Error(+ `${label} did not change the document; the editor rejected it. ${NOTHING_SAVED_HINT}`,+ );+ }++ current = next;+ }++ const snapshot = current;if (fallbackContent?.trim().length && snapshot.content.trim().length === 0) {throw new Error('Agent document node edit unexpectedly produced empty content');}- if (- operations.length > 0 &&- JSON.stringify(snapshot.editorData) === JSON.stringify(beforeSnapshot.editorData) &&- snapshot.litexml === beforeSnapshot.litexml- ) {- throw new Error('Agent document node edit did not change the document');- }-return { ...snapshot, previousEditorData: beforeSnapshot.editorData };} finally {editor.destroy();diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex d02c2645ff8..7cc5c7f10ab 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -117,6 +117,7 @@ describe('AgentDocumentsService', () => {listByDocumentIds: vi.fn(),rename: vi.fn(),update: vi.fn(),+ updateEditorSnapshotIfUnchanged: vi.fn(),upsert: vi.fn(),};const mockDocumentService = {@@ -150,6 +151,7 @@ describe('AgentDocumentsService', () => {beforeEach(() => {vi.clearAllMocks();+ mockModel.updateEditorSnapshotIfUnchanged.mockResolvedValue(true);(AgentDocumentModel as any).mockImplementation(function () {return mockModel;});@@ -278,7 +280,31 @@ describe('AgentDocumentsService', () => {expect(mockModel.create).not.toHaveBeenCalled();});- it('should extract H1 from markdown content as the document title', async () => {+ it('keeps the explicit title and the H1 body line when they differ', async () => {+ vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({+ content: 'body',+ title: 'FASE G-2D — INFORME DE CIERRE',+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'G-2D-CIERRE-20260922-1101' });++ const service = new AgentDocumentsService(db, userId);+ const content = '# FASE G-2D — INFORME DE CIERRE\n\nbody';+ await service.createDocument('agent-1', 'G-2D-CIERRE-20260922-1101', content);++ expect(vi.mocked(buildDocumentFilename)).toHaveBeenCalledWith('G-2D-CIERRE-20260922-1101');+ expect(mockModel.create).toHaveBeenCalledWith(+ 'agent-1',+ 'G-2D-CIERRE-20260922-1101',+ content,+ {+ editorData: { root: { children: [] } },+ title: 'G-2D-CIERRE-20260922-1101',+ },+ );+ });++ it('strips an H1 that duplicates the explicit title', async () => {vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({content: 'body',title: 'My Title',@@ -287,7 +313,24 @@ describe('AgentDocumentsService', () => {mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'My Title' });const service = new AgentDocumentsService(db, userId);- await service.createDocument('agent-1', 'fallback', '# My Title\n\nbody');+ await service.createDocument('agent-1', 'My Title', '# My Title\n\nbody');++ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'My Title', 'body', {+ editorData: { root: { children: [] } },+ title: 'My Title',+ });+ });++ it('falls back to the H1 as the title when no title is given', async () => {+ vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({+ content: 'body',+ title: 'My Title',+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'My Title' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument('agent-1', ' ', '# My Title\n\nbody');expect(vi.mocked(buildDocumentFilename)).toHaveBeenCalledWith('My Title');expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'My Title', 'body', {@@ -296,6 +339,17 @@ describe('AgentDocumentsService', () => {});});+ it('rejects LiteXML content instead of creating an empty document', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);++ const service = new AgentDocumentsService(db, userId);++ await expect(+ service.createDocument('agent-1', 'Doc', '<?xml version="1.0"?>\n<root><p>Body</p></root>'),+ ).rejects.toThrow('looks like LiteXML');+ expect(mockModel.create).not.toHaveBeenCalled();+ });+it('persists agent signal skill hints in document metadata', async () => {mockModel.findByParentAndFilename.mockResolvedValue(undefined);mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'Reusable Procedure' });@@ -699,6 +753,7 @@ describe('AgentDocumentsService', () => {.mockResolvedValueOnce(staleDocument).mockResolvedValueOnce(repairedDocument).mockResolvedValueOnce(modifiedDocument);+ mockModel.updateEditorSnapshotIfUnchanged.mockResolvedValueOnce(true);const service = new AgentDocumentsService(db, userId);const readResult = await service.getDocumentSnapshotById(agentDocumentId, 'agent-1');@@ -708,10 +763,11 @@ describe('AgentDocumentsService', () => {'agent-1',);- expect(mockModel.update).toHaveBeenNthCalledWith(1, agentDocumentId, {- content: 'fallback content',- editorData: repairedEditorData,- });+ expect(mockModel.updateEditorSnapshotIfUnchanged).toHaveBeenCalledWith(+ agentDocumentId,+ { content: 'fallback content', editorData: staleEditorData },+ { content: 'fallback content', editorData: repairedEditorData },+ );expect(readResult?.editorData).toEqual(repairedEditorData);expect(mockDocumentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith('documents-1',@@ -721,6 +777,46 @@ describe('AgentDocumentsService', () => {expect(modifyResult?.content).toBe('xml updated');});+ it('should not overwrite an autosave that lands between the read and the snapshot repair', async () => {+ const agentDocumentId = '11111111-1111-4111-8111-111111111111';+ // Nonempty document whose editorData is missing (legacy `lh doc` write),+ // so readDocument repairs it from Markdown and wants to persist the repair.+ const legacyDocument = {+ agentId: 'agent-1',+ content: 'stale body',+ documentId: 'documents-1',+ editorData: null,+ id: agentDocumentId,+ title: 'Doc',+ };+ // The mounted page autosaves a newer body before the repair is written.+ const autosavedEditorData = {+ root: { children: [{ text: 'newer body', type: 'text' }], type: 'root' },+ };+ const autosavedDocument = {+ ...legacyDocument,+ content: 'newer body',+ editorData: autosavedEditorData,+ };+ mockModel.findById.mockResolvedValueOnce(legacyDocument);+ mockModel.findById.mockResolvedValueOnce(autosavedDocument);+ mockModel.updateEditorSnapshotIfUnchanged.mockResolvedValueOnce(false);++ const service = new AgentDocumentsService(db, userId);+ const result = await service.getDocumentSnapshotById(agentDocumentId, 'agent-1');++ // The stale repair must only be written behind a version predicate.+ expect(mockModel.update).not.toHaveBeenCalled();+ expect(mockModel.updateEditorSnapshotIfUnchanged).toHaveBeenCalledTimes(1);+ expect(mockModel.updateEditorSnapshotIfUnchanged).toHaveBeenCalledWith(+ agentDocumentId,+ { content: 'stale body', editorData: null },+ { content: 'stale body', editorData: { root: { children: [] } } },+ );+ // The read is rebuilt from the autosaved version instead of the stale fetch.+ expect(result).toMatchObject({ content: 'projected', editorData: autosavedEditorData });+ });+it('should fall back to markdown content when editor data is empty', async () => {const agentDocumentId = '11111111-1111-4111-8111-111111111111';mockModel.findById.mockResolvedValue({@@ -864,6 +960,28 @@ lossless tool result});describe('replaceDocumentContentById', () => {+ it('rejects LiteXML content instead of saving an empty document', async () => {+ mockModel.findById.mockResolvedValueOnce({+ agentId: 'agent-1',+ content: 'old',+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ });++ const service = new AgentDocumentsService(db, userId);++ await expect(+ service.replaceDocumentContentById(+ 'agent-doc-1',+ '<?xml version="1.0" encoding="UTF-8"?>\n<root>\n <p id="rxam"></p>\n</root>',+ 'agent-1',+ ),+ ).rejects.toThrow('looks like LiteXML');+ expect(mockModel.update).not.toHaveBeenCalled();+ expect(mockDocumentService.trySaveCurrentDocumentHistory).not.toHaveBeenCalled();+ });+it('should save history before editing document content', async () => {mockModel.findById.mockResolvedValueOnce({@@ -966,13 +1084,11 @@ lossless tool resultcontent: 'xml updated',editorData: { root: { children: [] } },});- expect(headlessEditorMocks.applyLiteXML).toHaveBeenCalledWith([- {- action: 'replace',- delay: true,- litexml: '<p id="node-1">xml updated</p>',- },- ]);+ expect(headlessEditorMocks.applyLiteXML).toHaveBeenCalledWith({+ action: 'replace',+ delay: true,+ litexml: '<p id="node-1">xml updated</p>',+ });expect(headlessEditorMocks.applyLiteXMLBatch).not.toHaveBeenCalled();expect(result?.content).toBe('xml updated');});diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex a99a0548a72..b2a2e53e853 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -39,6 +39,7 @@ import { isRawTextAgentDocument } from './contentFormat';import {type AgentDocumentLiteXMLOperation,applyLiteXMLOperations,+ createAgentMarkdownSnapshot,createMarkdownEditorSnapshot,exportEditorDataSnapshot,} from './headlessEditor';@@ -131,6 +132,7 @@ const toAgentDocumentContextPayload = (): AgentDocumentContextPayload => ({content: doc.content,contentCharCount: doc.contentCharCount,+ createdAt: doc.createdAt,description: doc.description,documentId: doc.documentId,filename: doc.filename,@@ -227,7 +229,10 @@ export class AgentDocumentsService {);}- private async attachLiteXML(doc: AgentDocument): Promise<AgentDocumentWithLiteXML> {+ private async attachLiteXML(+ doc: AgentDocument,+ retriesLeft = 2,+ ): Promise<AgentDocumentWithLiteXML> {if (isRawTextAgentDocument(doc)) return doc;const snapshot = await exportEditorDataSnapshot({@@ -239,10 +244,25 @@ export class AgentDocumentsService {if (snapshot.recoveredFromMarkdown) {// Persist the repaired snapshot before exposing its LiteXML IDs. A later// node edit must hydrate this exact state or the IDs can no longer target it.- await this.agentDocumentModel.update(doc.id, {- content: snapshot.content,- editorData: snapshot.editorData,- });+ // The write is conditional on the version this repair was built from: a+ // save that landed after the fetch (e.g. the open page autosaving) must+ // not be overwritten by the stale repair, so re-read and rebuild instead.+ const persisted = await this.agentDocumentModel.updateEditorSnapshotIfUnchanged(+ doc.id,+ { content: doc.content, editorData: doc.editorData ?? null },+ { content: snapshot.content, editorData: snapshot.editorData },+ );++ if (!persisted) {+ const latest = retriesLeft > 0 ? await this.agentDocumentModel.findById(doc.id) : undefined;+ if (!latest) {+ throw new Error(+ 'The document changed while it was being read; nothing was overwritten. Read it again.',+ );+ }++ return this.attachLiteXML(latest, retriesLeft - 1);+ }return {...doc,@@ -290,7 +310,7 @@ export class AgentDocumentsService {suffix += 1;}- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(content);return this.agentDocumentModel.create(agentId, filename, snapshot.content, {...params,@@ -626,8 +646,11 @@ export class AgentDocumentsService {}}+ // The caller's explicit title wins; a leading H1 only names untitled documents.+ // The H1 is stripped from the body only when it duplicates the chosen title.const { title: extractedTitle, content: strippedContent } = extractMarkdownH1Title(content);- const finalTitle = extractedTitle || title;+ const finalTitle = title.trim() || extractedTitle || title;+ const finalContent = extractedTitle === finalTitle ? strippedContent : content;const metadata = options.hintIsSkill? {agentSignal: {@@ -637,7 +660,7 @@ export class AgentDocumentsService {}: undefined;- return this.createWithUniqueFilename(agentId, finalTitle, strippedContent, {+ return this.createWithUniqueFilename(agentId, finalTitle, finalContent, {...(metadata ? { metadata } : {}),...(options.parentId ? { parentId: options.parentId } : {}),});@@ -843,7 +866,7 @@ export class AgentDocumentsService {}) {const existing = await this.agentDocumentModel.findByFilename(agentId, filename);const projectedExisting = await this.projectDocumentContent(existing);- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(content);if (existing && projectedExisting?.content !== snapshot.content) {await this.documentService.trySaveCurrentDocumentHistory(existing.documentId, 'llm_call');@@ -857,7 +880,7 @@ export class AgentDocumentsService {async replaceDocumentContentById(documentId: string, content: string, expectedAgentId?: string) {const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);if (!doc) return undefined;- const snapshot = await createMarkdownEditorSnapshot(content);+ const snapshot = await createAgentMarkdownSnapshot(content);if (doc.content !== snapshot.content) {await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');diff --git a/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts b/apps/server/src/services/agentDocuments/modifyNodes.regression.test.tsnew file mode 100644index 00000000000..102980b991e--- /dev/null+++ b/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts@@ -0,0 +1,242 @@+// @vitest-environment node+// Regression cases reproduced from agent vent reports about modifyNodes / createDocument.+// Each case asserts the expected behaviour against the production headless editor path.+import { describe, expect, it } from 'vitest';++import type { AgentDocumentLiteXMLOperation } from './headlessEditor';+import {+ applyLiteXMLOperations,+ createAgentMarkdownSnapshot,+ createMarkdownEditorSnapshot,+ exportEditorDataSnapshot,+} from './headlessEditor';++const load = async (md: string) => {+ const s = await createMarkdownEditorSnapshot(md);+ return exportEditorDataSnapshot({+ editorData: s.editorData,+ fallbackContent: s.content,+ litexml: true,+ });+};++// Simulates the agent's read-back: persisted editorData re-hydrated by readDocument.+const editThenRead = async (+ base: Awaited<ReturnType<typeof load>>,+ operations: AgentDocumentLiteXMLOperation[],+) => {+ const r = await applyLiteXMLOperations({+ editorData: base.editorData,+ fallbackContent: base.content,+ operations,+ });+ return exportEditorDataSnapshot({+ editorData: r.editorData,+ fallbackContent: r.content,+ litexml: true,+ });+};++const liId = (xml: string, text: string) =>+ xml.match(new RegExp(`<li id="(\\w+)">\\s*<span id="\\w+">${text}</span>`))![1];+const blockId = (xml: string, tag: string, text: string) =>+ xml.match(new RegExp(`<${tag} id="(\\w+)">\\s*<span id="\\w+">${text}</span>`))![1];++const LIST = '# T\n\nintro\n\n- a\n- b\n - b1\n - b2\n- c\n\n## After\n\ntail\n';++describe('agent document modifyNodes regressions', () => {+ it('R1 insert <li> afterId keeps its children (listItemAdd diff is exported empty)', async () => {+ const base = await load(LIST);+ const back = await editThenRead(base, [+ { action: 'insert', afterId: liId(base.litexml!, 'a'), litexml: '<li><span>NEW</span></li>' },+ ]);+ expect(back.content).toContain('- NEW');+ });++ it('R2 insert <li> beforeId does not destroy siblings or duplicate the tail', async () => {+ const base = await load(LIST);+ const back = await editThenRead(base, [+ {+ action: 'insert',+ beforeId: liId(base.litexml!, 'c'),+ litexml: '<li><span>NEW</span></li>',+ },+ ]);+ expect(back.content).toContain('- c');+ expect(back.content.match(/## After/g)).toHaveLength(1);+ });++ it('R3 remove <li> actually removes the item (listItemRemove leaves an empty shell)', async () => {+ const base = await load(LIST);+ const back = await editThenRead(base, [{ action: 'remove', id: liId(base.litexml!, 'a') }]);+ expect(back.content).not.toMatch(/^-\s*$/m);+ });++ it('R4 multiple inserts with the same beforeId keep array order', async () => {+ const base = await load(LIST);+ const anchor = blockId(base.litexml!, 'p', 'tail');+ const back = await editThenRead(+ base,+ ['P1', 'P2', 'P3'].map((t) => ({+ action: 'insert' as const,+ beforeId: anchor,+ litexml: `<p><span>${t}</span></p>`,+ })),+ );+ expect(back.content.indexOf('P1')).toBeLessThan(back.content.indexOf('P3'));+ });++ it('R4b multiple inserts with the same afterId keep array order', async () => {+ const base = await load(LIST);+ const anchor = blockId(base.litexml!, 'p', 'intro');+ const back = await editThenRead(+ base,+ ['P1', 'P2', 'P3'].map((t) => ({+ action: 'insert' as const,+ afterId: anchor,+ litexml: `<p><span>${t}</span></p>`,+ })),+ );+ expect(back.content).toContain('intro\n\nP1\n\nP2\n\nP3\n\n- a');+ });++ it('R4d same-afterId inserts separated by an unrelated modify keep array order', async () => {+ const base = await load(LIST);+ const anchor = blockId(base.litexml!, 'p', 'intro');+ const tail = blockId(base.litexml!, 'p', 'tail');+ const back = await editThenRead(base, [+ { action: 'insert', afterId: anchor, litexml: '<p><span>P1</span></p>' },+ { action: 'modify', litexml: `<p id="${tail}"><span>TAIL</span></p>` },+ { action: 'insert', afterId: anchor, litexml: '<p><span>P2</span></p>' },+ ]);+ expect(back.content).toContain('intro\n\nP1\n\nP2\n\n- a');+ expect(back.content).toContain('TAIL');+ });++ it('R4c a paragraph and a list inserted after the same anchor keep order and review mode', async () => {+ const base = await load(LIST);+ const anchor = blockId(base.litexml!, 'p', 'intro');+ const result = await applyLiteXMLOperations({+ editorData: base.editorData,+ fallbackContent: base.content,+ operations: [+ { action: 'insert', afterId: anchor, litexml: '<p><span>Lead</span></p>' },+ { action: 'insert', afterId: anchor, litexml: '<ul><li><span>u1</span></li></ul>' },+ ],+ });++ expect(result.content).toContain('intro\n\nLead\n\n- u1');+ // Only the list is applied directly; the paragraph stays a pending review diff.+ expect(JSON.stringify(result.editorData)).toContain('"diffType":"add"');+ });++ it('R5 a stale/unknown id inside a batch is reported, not silently skipped', async () => {+ const base = await load(LIST);+ await expect(+ applyLiteXMLOperations({+ editorData: base.editorData,+ fallbackContent: base.content,+ operations: [+ { action: 'modify', litexml: '<span id="zzzz">stale</span>' },+ {+ action: 'insert',+ afterId: blockId(base.litexml!, 'p', 'tail'),+ litexml: '<p><span>ok</span></p>',+ },+ ],+ }),+ ).rejects.toThrow();+ });++ it('R6 CLI-written editorData {type:"doc",content}: an id returned by readDocument is still valid for modifyNodes', async () => {+ const md = '## Tick Log\n\n- tick 1\n';+ const editorData = { content: md, type: 'doc' }; // shape older `lh doc` builds persisted+ const read = await exportEditorDataSnapshot({ editorData, fallbackContent: md, litexml: true });+ // readDocument persists a recovered snapshot before exposing its ids, so the+ // next edit must hydrate that persisted state instead of re-parsing Markdown.+ expect(read.recoveredFromMarkdown).toBe(true);+ const h2 = read.litexml!.match(/<h2 id="(\w+)">/)![1];+ const r = await applyLiteXMLOperations({+ editorData: read.editorData,+ fallbackContent: read.content,+ operations: [{ action: 'insert', afterId: h2, litexml: '<p><span>NEW TICK</span></p>' }],+ });+ expect(r.content).toContain('NEW TICK');+ });++ it('R7 modifying the same <li> container twice keeps list structure', async () => {+ const base = await load('# T\n\n- one\n- two\n- three\n');+ const id = liId(base.litexml!, 'two');+ const once = await editThenRead(base, [+ { action: 'modify', litexml: `<li id="${id}"><span>two v2</span></li>` },+ ]);+ expect(once.content).toContain('- two v2\n');++ const twice = await editThenRead(once, [+ {+ action: 'modify',+ litexml: `<li id="${liId(once.litexml!, 'two v2')}"><span>two v3</span></li>`,+ },+ ]);+ expect(twice.content).toBe('# T\n\n- one\n- two v3\n- three\n');+ });++ // Upstream @lobehub/editor re-parses a modified node without keeping its key,+ // so the id changes after every modify. A stale id in a later batch is now+ // rejected loudly (R5); keeping the id needs the editor dependency to change.+ it.fails('R7b modifying a <li> keeps its id', async () => {+ const base = await load('# T\n\n- one\n- two\n- three\n');+ const id = liId(base.litexml!, 'two');+ const once = await editThenRead(base, [+ { action: 'modify', litexml: `<li id="${id}"><span>two v2</span></li>` },+ ]);+ expect(once.litexml).toContain(`id="${id}"`);+ });++ it('R8 modify of a whole <ul> keeps its items', async () => {+ const base = await load(LIST);+ const ul = base.litexml!.match(/<ul id="(\w+)">/)![1];+ const back = await editThenRead(base, [+ {+ action: 'modify',+ litexml: `<ul id="${ul}"><li><span>L1</span></li><li><span>L2</span></li></ul>`,+ },+ ]);+ expect(back.content).toContain('- L1');+ });++ it('R9 an inserted <ul> is not serialized as a fenced code block', async () => {+ const base = await load(LIST);+ const back = await editThenRead(base, [+ {+ action: 'insert',+ afterId: blockId(base.litexml!, 'p', 'intro'),+ litexml: '<h3>Sub</h3><ul><li><span>u1</span></li></ul>',+ },+ ]);+ expect(back.content).not.toContain('```');+ });+});++describe('agent document markdown writes regressions', () => {+ it('R10 LiteXML passed as markdown content must not silently become an empty document', async () => {+ await expect(+ createAgentMarkdownSnapshot(+ '<?xml version="1.0" encoding="UTF-8"?>\n<root>\n <p id="a"><span id="b">Body</span></p>\n</root>',+ ),+ ).rejects.toThrow(/LiteXML/);+ });++ // Upstream @lobehub/editor markdown writer bug (table cell text ending in a+ // backslash escapes the column separator). Kept as an expected failure so it+ // flips to a hard failure once the editor dependency fixes it.+ it.fails('R11 table cell text ending in a backslash keeps the column count', async () => {+ const base = await load('| a | b | c |\n| --- | --- | --- |\n| x | y | z |\n');+ const span = base.litexml!.match(/<span id="(\w+)">y<\/span>/)![1];+ const back = await editThenRead(base, [+ { action: 'modify', litexml: `<span id="${span}">D:\\lobechat\\{id}_search\\</span>` },+ ]);+ const header = back.content.split('\n')[0];+ expect(header.split('|').length - 2).toBe(3);+ });+});diff --git a/apps/server/src/services/document/editorData.test.ts b/apps/server/src/services/document/editorData.test.tsnew file mode 100644index 00000000000..a594de2a399--- /dev/null+++ b/apps/server/src/services/document/editorData.test.ts@@ -0,0 +1,57 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { isValidEditorData } from '@/libs/editor/isValidEditorData';++import { applyLiteXMLOperations, exportEditorDataSnapshot } from '../agentDocuments/headlessEditor';+import { resolveDocumentEditorData } from './editorData';++describe('resolveDocumentEditorData', () => {+ it('keeps valid Lexical editorData untouched', async () => {+ const editorData = { root: { children: [{ type: 'paragraph' }], type: 'root' } };++ await expect(resolveDocumentEditorData({ content: 'x', editorData })).resolves.toBe(editorData);+ });++ it('replaces the `{ type: "doc", content }` shape older CLI builds sent', async () => {+ const content = '## Tick Log\n\n- tick 1\n';+ const editorData = await resolveDocumentEditorData({+ content,+ editorData: { content, type: 'doc' },+ });++ expect(isValidEditorData(editorData)).toBe(true);+ });++ it('builds editorData when only content is sent, so node ids stay stable across reads', async () => {+ const content = '## Tick Log\n\n- tick 1\n';+ const editorData = await resolveDocumentEditorData({ content });++ const first = await exportEditorDataSnapshot({+ editorData,+ fallbackContent: content,+ litexml: true,+ });+ const second = await exportEditorDataSnapshot({+ editorData,+ fallbackContent: content,+ litexml: true,+ });+ expect(first.litexml).toBe(second.litexml);++ const h2 = first.litexml!.match(/<h2 id="(\w+)">/)![1];+ const edited = await applyLiteXMLOperations({+ editorData,+ fallbackContent: content,+ operations: [{ action: 'insert', afterId: h2, litexml: '<p><span>NEW TICK</span></p>' }],+ });+ expect(edited.content).toContain('NEW TICK');+ });++ it('leaves folders and metadata-only updates alone', async () => {+ await expect(+ resolveDocumentEditorData({ content: '', fileType: 'custom/folder' }),+ ).resolves.toBeUndefined();+ await expect(resolveDocumentEditorData({})).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/document/editorData.ts b/apps/server/src/services/document/editorData.tsnew file mode 100644index 00000000000..ba2829c578e--- /dev/null+++ b/apps/server/src/services/document/editorData.ts@@ -0,0 +1,32 @@+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';++import { isValidEditorData } from '@/libs/editor/isValidEditorData';++import { createMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';++interface ResolveDocumentEditorDataParams {+ content?: string;+ editorData?: Record<string, any>;+ fileType?: string;+}++/**+ * Resolve the editorData to persist alongside a Markdown `content` write.+ *+ * Clients that cannot build Lexical state (the CLI) send only content, and older+ * CLI builds sent `{ type: 'doc', content }`. Persisting either leaves every+ * reader to re-parse Markdown, which mints new node ids on each read, so the ids+ * an agent reads are gone by the time it edits nodes by id. Build real Lexical+ * state from the content instead; valid editorData is kept as-is.+ */+export const resolveDocumentEditorData = async ({+ content,+ editorData,+ fileType,+}: ResolveDocumentEditorDataParams): Promise<Record<string, any> | undefined> => {+ if (isValidEditorData(editorData)) return editorData;+ if (content === undefined || fileType === CUSTOM_FOLDER_FILE_TYPE) return editorData;++ const snapshot = await createMarkdownEditorSnapshot(content);+ return snapshot.editorData;+};diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex d6e5fe23359..4c4770548cc 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -194,7 +194,7 @@ export class DocumentService {*/async createDocument(params: {content?: string;- editorData: Record<string, any>;+ editorData?: Record<string, any>;fileType?: string;knowledgeBaseId?: string;metadata?: Record<string, any>;@@ -328,7 +328,7 @@ export class DocumentService {async createDocuments(documents: Array<{content?: string;- editorData: Record<string, any>;+ editorData?: Record<string, any>;fileType?: string;knowledgeBaseId?: string;metadata?: Record<string, any>;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.tsindex 38264f4c66d..e371f5958ac 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts@@ -4,7 +4,7 @@ import {type PageAgentInvocationContext,type PageAgentRuntimeService,} from '@lobechat/builtin-tool-page-agent/executionRuntime';-import { EditorRuntime } from '@lobechat/editor-runtime';+import { EditorRuntime, formatModifyNodesResult } from '@lobechat/editor-runtime';import { createHeadlessEditor, type HeadlessEditor } from '@lobehub/editor/headless';import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';@@ -345,21 +345,8 @@ const buildService = (modifyNodes: (args, ctx) =>withEditor(serviceCtx, 'modifyNodes', ctx, async ({ runtime }) => {const result = await runtime.modifyNodes(args);- const operations = Array.isArray(args.operations)- ? args.operations- : args.operations- ? [args.operations]- : [];- const actionSummary = operations.reduce<Record<string, number>>((acc, op) => {- if (!op) return acc;- acc[op.action] = (acc[op.action] || 0) + 1;- return acc;- }, {});- const summary = Object.entries(actionSummary)- .map(([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`)- .join(', ');return {- content: `Successfully executed ${summary} (${result.successCount}/${result.totalCount} operations succeeded).`,+ content: formatModifyNodesResult(result),state: {results: result.results,successCount: result.successCount,diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex 1e310e62e9c..49085817ab6 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -504,6 +504,9 @@ export class AgentDocumentsExecutionRuntime {});if (!updated) return { content: `Failed to modify document ${args.id}.`, success: false };+ // The service applies the batch atomically: an unknown id or an operation the+ // editor rejects throws with that operation's position, and nothing is saved.+ // Reaching this point therefore means every operation was applied.const results = operations.map((operation) => ({action: operation.action,success: true,diff --git a/packages/builtin-tool-page-agent/src/client/executor/index.ts b/packages/builtin-tool-page-agent/src/client/executor/index.tsindex 9d449efea70..ad4ba366225 100644--- a/packages/builtin-tool-page-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.ts@@ -6,6 +6,7 @@ import type {ModifyNodesArgs,ReplaceTextArgs,} from '@lobechat/editor-runtime';+import { formatModifyNodesResult } from '@lobechat/editor-runtime';import type { BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import debug from 'debug';@@ -322,19 +323,7 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {try {const result = await this.runtime.modifyNodes(params);- // Build summary message- const actionSummary = params.operations.reduce(- (acc, op) => {- acc[op.action] = (acc[op.action] || 0) + 1;- return acc;- },- {} as Record<string, number>,- );-- const summaryParts = Object.entries(actionSummary).map(- ([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`,- );- const content = `Successfully executed ${summaryParts.join(', ')} (${result.successCount}/${result.totalCount} operations succeeded).`;+ const content = formatModifyNodesResult(result);const state: ModifyNodesState = {results: result.results,diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.tsindex 92b8483720b..af9bbcf5886 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts@@ -3,7 +3,7 @@ import debug from 'debug';import { BaseProcessor } from '../../base/BaseProcessor';import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';-import { combineDocuments, getDocumentsForPositions } from './shared';+import { combineDocuments, getDocumentsForPositions, withRunStartedAt } from './shared';const log = debug('context-engine:provider:AgentDocumentBeforeSystemInjector');@@ -40,7 +40,7 @@ export class AgentDocumentBeforeSystemInjector extends BaseProcessor {if (docs.length === 0) return this.markAsExecuted(context);const clonedContext = this.cloneContext(context);- const content = combineDocuments(docs, this.config);+ const content = combineDocuments(docs, withRunStartedAt(this.config, context.messages));const now = Date.now();clonedContext.messages.unshift({diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.tsindex 9d1a84dc7a1..b7627958686 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts@@ -3,7 +3,7 @@ import debug from 'debug';import { BaseFirstUserContentProvider } from '../../base/BaseFirstUserContentProvider';import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';-import { combineDocuments, getDocumentsForPositions } from './shared';+import { combineDocuments, getDocumentsForPositions, withRunStartedAt } from './shared';const log = debug('context-engine:provider:AgentDocumentContextInjector');@@ -28,7 +28,7 @@ export class AgentDocumentContextInjector extends BaseFirstUserContentProvider {super(options);}- protected buildContent(_context: PipelineContext): string | null {+ protected buildContent(context: PipelineContext): string | null {if (this.config.enabled === false) return null;const docs = getDocumentsForPositions(@@ -40,6 +40,6 @@ export class AgentDocumentContextInjector extends BaseFirstUserContentProvider {if (docs.length === 0) return null;log('Injecting %d agent documents before first user message', docs.length);- return combineDocuments(docs, this.config);+ return combineDocuments(docs, withRunStartedAt(this.config, context.messages));}}diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.tsindex 20f3193e3e7..2ef5655a092 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts@@ -3,7 +3,7 @@ import debug from 'debug';import { BaseProcessor } from '../../base/BaseProcessor';import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';-import { combineDocuments, getDocumentsForPositions } from './shared';+import { combineDocuments, getDocumentsForPositions, withRunStartedAt } from './shared';const log = debug('context-engine:provider:AgentDocumentMessageInjector');@@ -47,7 +47,10 @@ export class AgentDocumentMessageInjector extends BaseProcessor {if (afterFirstUserDocs.length > 0) {const firstUserIndex = clonedContext.messages.findIndex((m) => m.role === 'user');if (firstUserIndex !== -1) {- const content = combineDocuments(afterFirstUserDocs, this.config);+ const content = combineDocuments(+ afterFirstUserDocs,+ withRunStartedAt(this.config, clonedContext.messages),+ );const now = Date.now();clonedContext.messages.splice(firstUserIndex + 1, 0, {content,@@ -62,7 +65,10 @@ export class AgentDocumentMessageInjector extends BaseProcessor {// Inject at context endif (contextEndDocs.length > 0) {- const content = combineDocuments(contextEndDocs, this.config);+ const content = combineDocuments(+ contextEndDocs,+ withRunStartedAt(this.config, clonedContext.messages),+ );const now = Date.now();clonedContext.messages.push({content,diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.tsindex 1970bd52f85..568dba8e2d6 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts@@ -3,7 +3,7 @@ import debug from 'debug';import { BaseSystemRoleProvider } from '../../base/BaseSystemRoleProvider';import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';-import { combineDocuments, getDocumentsForPositions } from './shared';+import { combineDocuments, getDocumentsForPositions, withRunStartedAt } from './shared';const log = debug('context-engine:provider:AgentDocumentSystemAppendInjector');@@ -28,7 +28,7 @@ export class AgentDocumentSystemAppendInjector extends BaseSystemRoleProvider {super(options);}- protected buildSystemRoleContent(_context: PipelineContext): string | null {+ protected buildSystemRoleContent(context: PipelineContext): string | null {if (this.config.enabled === false) return null;const docs = getDocumentsForPositions(@@ -40,6 +40,6 @@ export class AgentDocumentSystemAppendInjector extends BaseSystemRoleProvider {if (docs.length === 0) return null;log('Appending %d agent documents to system message', docs.length);- return combineDocuments(docs, this.config);+ return combineDocuments(docs, withRunStartedAt(this.config, context.messages));}}diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.tsindex 350fd008f55..4c1dbb95a90 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts@@ -3,7 +3,7 @@ import debug from 'debug';import { BaseProcessor } from '../../base/BaseProcessor';import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';-import { combineDocuments, getDocumentsForPositions } from './shared';+import { combineDocuments, getDocumentsForPositions, withRunStartedAt } from './shared';declare module '../../types' {interface PipelineContextMetadataOverrides {@@ -55,7 +55,7 @@ export class AgentDocumentSystemReplaceInjector extends BaseProcessor {if (docs.length === 0) return this.markAsExecuted(context);const clonedContext = this.cloneContext(context);- const content = combineDocuments(docs, this.config);+ const content = combineDocuments(docs, withRunStartedAt(this.config, context.messages));const now = Date.now();const message = {content,diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts b/packages/context-engine/src/providers/AgentDocumentInjector/index.tsindex 30c4f2fc55b..3e719c5509a 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts@@ -17,6 +17,7 @@ export {formatDocument,getDocumentsForPositions,sortByPriority,+ withRunStartedAt,} from './shared';export type { AgentDocumentSystemAppendInjectorConfig } from './SystemAppendInjector';export { AgentDocumentSystemAppendInjector } from './SystemAppendInjector';diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.tsindex 12213a7c886..bb2048564d2 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts@@ -29,6 +29,7 @@ export type AgentDocumentSourceType = 'agent' | 'agent-signal' | 'api' | 'file'export interface AgentContextDocument {content?: string;contentCharCount?: number;+ createdAt?: Date | string;description?: string;filename: string;/**@@ -58,9 +59,37 @@ export interface AgentContextDocument {export interface AgentDocumentFilterContext {currentTime?: Date;currentUserMessage?: string;+ /**+ * When the current run started. Documents created at or after it are marked in+ * the progressive index; the index is rebuilt every step, so without a marker a+ * document the agent just created looks like one that already existed.+ */+ runStartedAt?: Date | number | string;truncateContent?: (content: string, maxTokens: number) => string;}+const toTime = (value: Date | number | string | undefined): number | undefined => {+ if (value === undefined) return undefined;+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime();+ return Number.isNaN(time) ? undefined : time;+};++/**+ * Anchor the run to the latest user message: everything the agent did after it+ * belongs to the current run. An explicit `runStartedAt` wins.+ */+export function withRunStartedAt<T extends AgentDocumentFilterContext>(+ context: T,+ messages: { createdAt?: Date | number | string; role: string }[],+): T {+ if (context.runStartedAt !== undefined) return context;++ const lastUserMessage = messages.findLast((message) => message.role === 'user');+ return lastUserMessage?.createdAt === undefined+ ? context+ : { ...context, runStartedAt: lastUserMessage.createdAt };+}+/*** Filter documents by load rules (always, by-keywords, by-regexp, by-time-range)*/@@ -166,19 +195,37 @@ function truncate(s: string, max: number): string {return s.length > max ? `${s.slice(0, max - 1)}…` : s;}+const CREATED_THIS_RUN_MARK = '(created this run)';++/** Collapsed folders hide their rows, so the folder summary carries the count instead. */+const withCreatedThisRunCount = (summary: string, count: number) =>+ count > 0 ? `${summary} (${count} created this run)` : summary;++function isCreatedThisRun(doc: AgentContextDocument, context: AgentDocumentFilterContext) {+ const runStartedAt = toTime(context.runStartedAt);+ const createdAt = toTime(doc.createdAt);+ return runStartedAt !== undefined && createdAt !== undefined && createdAt >= runStartedAt;+}+/*** Render a list of progressive docs as a fixed-width table:** TITLE ID SIZE UPDATED* daily-brief.txt 2af6eb88-8bdb-468f-887f-620baa394efa 1.4k 2026-04-27*/-function buildIndexTable(docs: AgentContextDocument[]): string {- const rows = docs.map((d) => ({- id: d.id ?? '',- size: formatSize(d),- title: truncate(pickRowTitle(d), TITLE_MAX_WIDTH),- updated: formatUpdatedDate(d.updatedAt),- }));+function buildIndexTable(+ docs: AgentContextDocument[],+ context: AgentDocumentFilterContext,+): string {+ const rows = docs.map((d) => {+ const title = truncate(pickRowTitle(d), TITLE_MAX_WIDTH);+ return {+ id: d.id ?? '',+ size: formatSize(d),+ title: isCreatedThisRun(d, context) ? `${title} ${CREATED_THIS_RUN_MARK}` : title,+ updated: formatUpdatedDate(d.updatedAt),+ };+ });const titleWidth = Math.max('TITLE'.length, ...rows.map((r) => r.title.length));const idWidth = Math.max('ID'.length, ...rows.map((r) => r.id.length));@@ -275,11 +322,14 @@ function formatFolderSummary(docs: AgentContextDocument[]): string {* The ID column is the folder's `documentId` — the value the model passes to* `listDocuments(parentId=…)` to expand the folder on demand.*/-function buildFolderTable(folders: FolderGroup[]): string {+function buildFolderTable(folders: FolderGroup[], context: AgentDocumentFilterContext): string {const rows = folders.map((f) => ({id: f.parentId,- summary: formatFolderSummary(f.docs),+ summary: withCreatedThisRunCount(+ formatFolderSummary(f.docs),+ f.docs.filter((doc) => isCreatedThisRun(doc, context)).length,+ ),time: newestTime(f.docs),title: `${FOLDER_ICON} ${truncate(f.title, TITLE_MAX_WIDTH)}`,}))@@ -360,6 +410,11 @@ export function combineDocuments(`Web-crawled docs are available but omitted here — call listDocuments(sourceType='web') to discover them.`,);}+ if (userDocs.some((doc) => isCreatedThisRun(doc, context))) {+ headerLines.push(+ `Docs marked ${CREATED_THIS_RUN_MARK} (or counted that way in a folder row) did not exist before this run — you created them, so creating them did not overwrite an existing doc.`,+ );+ }if (folders.length > 0) {headerLines.push(`${folders.length} folder${folders.length === 1 ? '' : 's'} collapsed (${FOLDER_ICON}) — call listDocuments(parentId=<id>) to list a folder's docs.`,@@ -367,8 +422,8 @@ export function combineDocuments(}const bodyBlocks: string[] = [];- if (flat.length > 0) bodyBlocks.push(buildIndexTable(sortByRecency(flat)));- if (folders.length > 0) bodyBlocks.push(buildFolderTable(folders));+ if (flat.length > 0) bodyBlocks.push(buildIndexTable(sortByRecency(flat), context));+ if (folders.length > 0) bodyBlocks.push(buildFolderTable(folders, context));const tableBlock = bodyBlocks.length > 0 ? `\n\n${bodyBlocks.join('\n\n')}` : '';parts.push(diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.tsindex af0079c3653..46b11f08e76 100644--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts@@ -226,6 +226,84 @@ describe('AgentDocumentInjector', () => {expect(result.messages[0].content).not.toContain('Full content that should NOT appear');});+ // The index is rebuilt every step, so a doc the agent created earlier in the+ // same run showed up as if it already existed and was read as "overwritten".+ it('marks docs created during the current run in the progressive index', async () => {+ const runStartedAt = new Date('2026-09-23T22:57:30.000Z').getTime();+ const provider = new AgentDocumentContextInjector({+ documents: [+ {+ createdAt: new Date('2026-09-23T22:57:58.000Z'),+ filename: 'fase-g-2c.md',+ id: 'ce2c4f3a',+ loadPosition: 'before-first-user',+ loadRules: { rule: 'always' },+ policyLoad: 'progressive',+ title: 'FASE G-2C',+ updatedAt: new Date('2026-09-23T22:57:58.000Z'),+ },+ {+ createdAt: new Date('2026-09-21T23:12:00.000Z'),+ filename: 'fase-g-2b.md',+ id: '452eea73',+ loadPosition: 'before-first-user',+ loadRules: { rule: 'always' },+ policyLoad: 'progressive',+ title: 'FASE G-2B',+ updatedAt: new Date('2026-09-21T23:12:00.000Z'),+ },+ ],+ });++ const context = createContext([+ { content: 'earlier', createdAt: runStartedAt - 3_600_000, id: 'user-0', role: 'user' },+ { content: 'ok', createdAt: runStartedAt - 3_500_000, id: 'a-0', role: 'assistant' },+ { content: 'Write the G-2C report', createdAt: runStartedAt, id: 'user-1', role: 'user' },+ ]);+ const result = await provider.process(context);++ expect(result.messages[0].content).toMatchInlineSnapshot(`+ "<agent_documents_index>+ User-created docs, when present, are listed below — use readDocument(id) for full content.+ Docs marked (created this run) (or counted that way in a folder row) did not exist before this run — you created them, so creating them did not overwrite an existing doc.++ TITLE ID SIZE UPDATED+ FASE G-2C (created this run) ce2c4f3a empty 2026-09-23+ FASE G-2B 452eea73 empty 2026-09-21+ </agent_documents_index>"+ `);+ });++ it('counts docs created during the current run inside collapsed folders', async () => {+ const runStartedAt = new Date('2026-09-23T22:57:30.000Z').getTime();+ const inFolder = (id: string, createdAt: string) => ({+ createdAt: new Date(createdAt),+ filename: `${id}.md`,+ folderTitle: 'Reports',+ id,+ loadPosition: 'before-first-user' as const,+ loadRules: { rule: 'always' as const },+ parentId: 'folder-1',+ policyLoad: 'progressive' as const,+ title: id,+ updatedAt: new Date(createdAt),+ });+ const provider = new AgentDocumentContextInjector({+ documents: [+ inFolder('new-report', '2026-09-23T22:57:58.000Z'),+ inFolder('old-report', '2026-09-21T23:12:00.000Z'),+ ],+ });++ const result = await provider.process(+ createContext([{ content: 'go', createdAt: runStartedAt, id: 'user-1', role: 'user' }]),+ );+ const content = result.messages[0].content as string;++ expect(content).toContain('did not exist before this run');+ expect(content).toMatch(/📁 Reports\s+folder-1\s+2 docs \(1 created this run\)/);+ });+// https://github.com/lobehub/lobehub/issues/15624 — relative times ("15m ago")// in the index changed the prompt prefix every minute and broke provider-side// prompt caching. The index must stay byte-identical as wall-clock time passes.diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex 9ef162746a2..b904b950e76 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -595,6 +595,62 @@ describe('AgentDocumentModel', () => {});});+ describe('updateEditorSnapshotIfUnchanged', () => {+ const repaired = {+ content: 'body',+ editorData: { root: { children: [{ type: 'paragraph' }], type: 'root' } },+ };++ it('writes the repaired snapshot when the document still matches the read version', async () => {+ const created = await agentDocumentModel.create(agentId, 'repair.md', 'body');+ const read = (await agentDocumentModel.findById(created.id))!;++ const written = await agentDocumentModel.updateEditorSnapshotIfUnchanged(+ created.id,+ { content: read.content, editorData: read.editorData },+ repaired,+ );++ expect(written).toBe(true);+ const after = await agentDocumentModel.findById(created.id);+ expect(after?.editorData).toEqual(repaired.editorData);+ });++ it('does not overwrite a save that landed after the read', async () => {+ const created = await agentDocumentModel.create(agentId, 'repair.md', 'body');+ const read = (await agentDocumentModel.findById(created.id))!;+ const autosaved = { root: { children: [{ text: 'newer' }], type: 'root' } };+ await agentDocumentModel.update(created.id, { content: 'newer', editorData: autosaved });++ const written = await agentDocumentModel.updateEditorSnapshotIfUnchanged(+ created.id,+ { content: read.content, editorData: read.editorData },+ repaired,+ );++ expect(written).toBe(false);+ const after = await agentDocumentModel.findById(created.id);+ expect(after?.content).toBe('newer');+ expect(after?.editorData).toEqual(autosaved);+ });++ it('treats an editorData-only save as a new version', async () => {+ const created = await agentDocumentModel.create(agentId, 'repair.md', 'body');+ const read = (await agentDocumentModel.findById(created.id))!;+ const autosaved = { root: { children: [{ text: 'body' }], type: 'root' } };+ await agentDocumentModel.update(created.id, { editorData: autosaved });++ const written = await agentDocumentModel.updateEditorSnapshotIfUnchanged(+ created.id,+ { content: read.content, editorData: read.editorData },+ repaired,+ );++ expect(written).toBe(false);+ expect((await agentDocumentModel.findById(created.id))?.editorData).toEqual(autosaved);+ });+ });+describe('rename and copy', () => {it('should rename and preserve human-readable filename/source', async () => {const created = await agentDocumentModel.create(agentId, 'old-name.md', 'hello');diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex 6ea44186dd3..234627356af 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -639,6 +639,56 @@ export class AgentDocumentModel {: undefined;}+ /**+ * Writes a repaired editor snapshot only if the backing document still holds+ * the version the repair was computed from.+ *+ * Use when:+ * - A read path rebuilds `editorData` from Markdown and must persist it so the+ * node ids it exposes stay addressable, without clobbering a concurrent save.+ *+ * Expects:+ * - `expected` is the `content` / `editorData` pair the caller read.+ *+ * Returns:+ * - `true` when the snapshot was written; `false` when the document changed+ * (or is gone) since it was read, in which case nothing is written.+ */+ async updateEditorSnapshotIfUnchanged(+ documentId: string,+ expected: { content: string; editorData: Record<string, any> | null },+ next: { content: string; editorData: Record<string, any> },+ ): Promise<boolean> {+ const existing = await this.findById(documentId);+ if (!existing) return false;++ const stats = this.getDocumentStats(next.content);+ const expectedEditorData =+ expected.editorData === null || expected.editorData === undefined+ ? null+ : JSON.stringify(expected.editorData);++ const updated = await this.db+ .update(documents)+ .set({+ content: next.content,+ editorData: next.editorData,+ totalCharCount: stats.totalCharCount,+ totalLineCount: stats.totalLineCount,+ })+ .where(+ and(+ eq(documents.id, existing.documentId),+ this.documentOwnership(),+ sql`coalesce(${documents.content}, '') = ${expected.content}`,+ sql`${documents.editorData} IS NOT DISTINCT FROM ${expectedEditorData}::jsonb`,+ ),+ )+ .returning({ id: documents.id });++ return updated.length > 0;+ }+async update(documentId: string,params?: {@@ -1152,6 +1202,7 @@ export class AgentDocumentModel {},settings: {agentId: agentDocuments.agentId,+ createdAt: agentDocuments.createdAt,documentId: agentDocuments.documentId,id: agentDocuments.id,policy: agentDocuments.policy,@@ -1182,6 +1233,7 @@ export class AgentDocumentModel {> = {content: doc.content,contentCharCount: doc.totalCharCount,+ createdAt: settings.createdAt,description: doc.description ?? null,documentId: settings.documentId,editorData: doc.editorData ?? null,diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.tsindex b7c8f1ea45d..347bc62af3e 100644--- a/packages/database/src/models/agentDocuments/types.ts+++ b/packages/database/src/models/agentDocuments/types.ts@@ -103,6 +103,7 @@ export interface AgentDocumentListItem extends AgentDocumentDerivedFields {export interface AgentDocumentContextRow extends AgentDocumentDerivedFields {content: string;contentCharCount?: number;+ createdAt?: Date;description: string | null;documentId: string;editorData: Record<string, any> | null;@@ -125,6 +126,7 @@ export interface AgentDocumentContextRow extends AgentDocumentDerivedFields {export interface AgentDocumentContextPayload {content: string;contentCharCount?: number;+ createdAt?: Date;description: string | null;documentId: string;filename: string;diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex 2d8e9386528..e3ae4d783ad 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -1,8 +1,21 @@import type { PageContentContext } from '@lobechat/prompts';import type { IEditor } from '@lobehub/editor';-import { LITEXML_APPLY_COMMAND, LITEXML_MODIFY_COMMAND } from '@lobehub/editor/litexml-commands';+import {+ LITEXML_APPLY_COMMAND,+ LITEXML_INSERT_COMMAND,+ LITEXML_MODIFY_COMMAND,+ LITEXML_REMOVE_COMMAND,+} from '@lobehub/editor/litexml-commands';import debug from 'debug';+import {+ describeLiteXMLEditStep,+ findLiteXMLEditStepProblem,+ indexLiteXMLDocument,+ normalizeLiteXMLFragment,+ planLiteXMLEditSteps,+ touchesList,+} from './liteXMLEditPlan';import type {EditTitleArgs,EditTitleRuntimeResult,@@ -12,6 +25,7 @@ import type {InitPageRuntimeResult,ModifyNodesArgs,ModifyNodesRuntimeResult,+ ModifyOperation,ModifyOperationResult,ReplaceTextArgs,ReplaceTextRuntimeResult,@@ -19,6 +33,9 @@ import type {const log = debug('lobe:editor-runtime');+/** Lexical commits an update on the next microtask; wait for it before reading back. */+const nextMicrotask = () => new Promise<void>((resolve) => queueMicrotask(resolve));+interface InspectableEditor {dataTypeMap?: Map<string, unknown> | Record<string, unknown>;editor?: unknown;@@ -392,7 +409,7 @@ export class EditorRuntime {// ==================== Unified Node Operations ====================/**- * Unified node operations API using LITEXML_MODIFY_COMMAND.+ * Unified node operations API over the LiteXML editor commands.* Supports insert, modify, and remove operations in a single call.* @returns Raw result with results, successCount and totalCount*/@@ -426,73 +443,66 @@ export class EditorRuntime {log('Processing operations:', operations.length);- // Build the command payload for LITEXML_MODIFY_COMMAND- const commandPayload: Array<- | { action: 'insert'; afterId: string; litexml: string }- | { action: 'insert'; beforeId: string; litexml: string }- | { action: 'modify'; litexml: string | string[] }- | { action: 'remove'; id: string }- > = [];+ if (!hasDataSource(editor as InspectableEditor, 'litexml')) {+ throw new Error('modifyNodes failed: LiteXML data source is not ready.');+ }- const results: ModifyOperationResult[] = [];+ const results: ModifyOperationResult[] = operations.map((op) => ({+ action: op.action,+ success: false,+ }));+ const readLiteXML = () => editor.getDocument('litexml') as unknown as string;++ // Dispatch one step at a time and confirm each changed the page before+ // reporting it: the editor drops operations with unknown ids (or that it+ // cannot apply) without an error.+ // A step may apply only part of one operation (a split `modify`), so an+ // operation succeeds only when none of its steps failed.+ for (const step of planLiteXMLEditSteps(operations, indexLiteXMLDocument(readLiteXML()))) {+ const fail = (error: string) => {+ for (const index of step.indexes) {+ results[index] = { ...results[index], error, success: false };+ }+ };- for (const op of operations) {try {- switch (op.action) {- case 'insert': {- if ('beforeId' in op) {- commandPayload.push({- action: 'insert',- beforeId: op.beforeId,- litexml: op.litexml,- });- } else if ('afterId' in op) {- commandPayload.push({- action: 'insert',- afterId: op.afterId,- litexml: op.litexml,- });- } else {- throw new Error(- `Insert operation requires either 'beforeId' or 'afterId'. Got: ${JSON.stringify(Object.keys(op))}.`,- );- }- results.push({ action: 'insert', success: true });- break;- }-- case 'modify': {- commandPayload.push({- action: 'modify',- litexml: op.litexml,- });- results.push({ action: 'modify', success: true });- break;- }-- case 'remove': {- commandPayload.push({- action: 'remove',- id: op.id,- });- results.push({ action: 'remove', success: true });- break;- }+ const { operation } = step;+ if (operation.action === 'insert' && !('beforeId' in operation || 'afterId' in operation)) {+ throw new Error(+ `Insert operation requires either 'beforeId' or 'afterId'. Got: ${JSON.stringify(Object.keys(operation))}.`,+ );+ }++ const before = readLiteXML();+ const document = indexLiteXMLDocument(before);+ const problem = findLiteXMLEditStepProblem(operation, document);+ if (problem)+ throw new Error(`${describeLiteXMLEditStep(step, operations.length)}: ${problem}`);++ log('Dispatching LiteXML operation:', operation);+ this.dispatchLiteXMLOperation(editor, operation, !touchesList(operation, document));+ await nextMicrotask();++ if (readLiteXML() === before) {+ throw new Error(+ `${describeLiteXMLEditStep(step, operations.length)} did not change the page; the editor rejected it.`,+ );+ }++ for (const index of step.indexes) {+ if (!results[index].error) results[index] = { ...results[index], success: true };}} catch (error) {const err = error as Error;- console.error('[modifyNodes] Error processing operation:', op.action, err.message);- results.push({ action: op.action, error: err.message, success: false });+ console.error(+ '[modifyNodes] Error processing operation:',+ step.operation.action,+ err.message,+ );+ fail(err.message);}}- if (!hasDataSource(editor as InspectableEditor, 'litexml')) {- throw new Error('modifyNodes failed: LiteXML data source is not ready.');- }-- log('Dispatching LiteXML modify batch with payload:', commandPayload);- editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);-const successCount = results.filter((r) => r.success).length;const totalCount = results.length;@@ -508,6 +518,38 @@ export class EditorRuntime {return result;}+ /**+ * Edits that touch a list skip the pending review diff: @lobehub/editor's+ * list-item diffs serialize as empty items and lose list structure.+ */+ private dispatchLiteXMLOperation(editor: IEditor, operation: ModifyOperation, delay: boolean) {+ if (delay) {+ editor.dispatchCommand(LITEXML_MODIFY_COMMAND, [operation]);+ return;+ }++ switch (operation.action) {+ case 'insert': {+ const litexml = normalizeLiteXMLFragment(operation.litexml);+ editor.dispatchCommand(+ LITEXML_INSERT_COMMAND,+ 'beforeId' in operation+ ? { beforeId: operation.beforeId, delay: false, litexml }+ : { afterId: operation.afterId, delay: false, litexml },+ );+ return;+ }+ case 'modify': {+ editor.dispatchCommand(LITEXML_APPLY_COMMAND, { delay: false, litexml: operation.litexml });+ return;+ }+ case 'remove': {+ editor.dispatchCommand(LITEXML_REMOVE_COMMAND, { delay: false, id: operation.id });+ return;+ }+ }+ }+// ==================== Text Operations ====================/**diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.tsindex 786d3b11ee0..bc7fec89eb0 100644--- a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts@@ -180,6 +180,130 @@ describe('EditorRuntime - Real Cases', () => {});});+ // Regressions from agent vent reports: the page agent reported every operation+ // as applied before dispatching, and the batched command reversed inserts that+ // share a beforeId and emptied list items added as review diffs.+ describe('modifyNodes - per-operation results', () => {+ const liteXML = () => editor.getDocument('litexml') as unknown as string;+ const idOf = (tag: string, text: string) =>+ liteXML().match(new RegExp(`<${tag} id="(\\w+)">\\s*<span id="\\w+">${text}</span>`))![1];++ beforeEach(async () => {+ editor.setDocument('markdown', 'intro\n\n- a\n- b\n\ntail\n');+ await moment();+ });++ it('reports an operation with an unknown id as failed', async () => {+ const result = await runtime.modifyNodes({+ operations: [+ { action: 'modify', litexml: '<p id="zzzz">stale</p>' },+ { action: 'insert', afterId: idOf('p', 'tail'), litexml: '<p>ok</p>' },+ ],+ });++ expect(result.successCount).toBe(1);+ expect(result.results[0]).toMatchObject({ action: 'modify', success: false });+ expect(result.results[0].error).toContain('"zzzz" not found');+ expect(result.results[1]).toMatchObject({ action: 'insert', success: true });+ });++ it('keeps array order for inserts sharing a beforeId', async () => {+ const anchor = idOf('p', 'tail');+ const result = await runtime.modifyNodes({+ operations: ['P1', 'P2', 'P3'].map((text) => ({+ action: 'insert' as const,+ beforeId: anchor,+ litexml: `<p>${text}</p>`,+ })),+ });++ expect(result.successCount).toBe(3);+ const xml = liteXML();+ expect(xml.indexOf('P1')).toBeLessThan(xml.indexOf('P2'));+ expect(xml.indexOf('P2')).toBeLessThan(xml.indexOf('P3'));+ });++ it('keeps array order for inserts sharing an afterId', async () => {+ const anchor = idOf('p', 'intro');+ await runtime.modifyNodes({+ operations: ['P1', 'P2', 'P3'].map((text) => ({+ action: 'insert' as const,+ afterId: anchor,+ litexml: `<p>${text}</p>`,+ })),+ });++ const xml = liteXML();+ expect(xml.indexOf('P1')).toBeLessThan(xml.indexOf('P2'));+ expect(xml.indexOf('P2')).toBeLessThan(xml.indexOf('P3'));+ });++ it('does not report inserts erased by a later replacement of the enclosing list as applied', async () => {+ const anchor = idOf('li', 'a');+ const list = liteXML().match(/<ul id="\w+">[\s\S]*?<\/ul>/)![0];+ const result = await runtime.modifyNodes({+ operations: [+ { action: 'insert', afterId: anchor, litexml: '<li><span>A</span></li>' },+ { action: 'modify', litexml: list.replace('>b</span>', '>b2</span>') },+ { action: 'insert', afterId: anchor, litexml: '<li><span>B</span></li>' },+ ],+ });++ // Applied in caller order: the list replacement drops A and re-keys the+ // list, so the later insert is reported as failed instead of vanishing+ // behind a success.+ expect(result.results.map((r) => r.success)).toEqual([true, true, false]);+ expect(result.results[2].error).toContain('not found');+ expect(editor.getDocument('markdown') as unknown as string).toContain('- b2');+ });++ it('rejects a multi-fragment modify that replaces a list and an item inside it', async () => {+ const item = idOf('li', 'b');+ const list = liteXML().match(/<ul id="\w+">[\s\S]*?<\/ul>/)![0];+ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'modify',+ litexml: [+ list.replace('>a</span>', '>a2</span>'),+ `<li id="${item}"><span>b2</span></li>`,+ ],+ },+ ],+ });++ // Replacing the list re-keys its items, so the item fragment would be+ // dropped while the list change made the whole step look applied.+ expect(result.results[0]).toMatchObject({ success: false });+ expect(result.results[0].error).toContain(`encloses node "${item}"`);+ expect(editor.getDocument('markdown') as unknown as string).toContain('- a\n');+ });++ it('reports an empty insert as failed even when merged with a real one', async () => {+ const anchor = idOf('p', 'intro');+ const result = await runtime.modifyNodes({+ operations: [+ { action: 'insert', afterId: anchor, litexml: '' },+ { action: 'insert', afterId: anchor, litexml: '<p>B</p>' },+ ],+ });++ expect(result.results[0]).toMatchObject({ success: false });+ expect(result.results[1]).toMatchObject({ success: true });+ });++ it('keeps the text of an inserted list item', async () => {+ const result = await runtime.modifyNodes({+ operations: [+ { action: 'insert', afterId: idOf('li', 'a'), litexml: '<li><span>NEW</span></li>' },+ ],+ });++ expect(result.successCount).toBe(1);+ expect(editor.getDocument('markdown') as unknown as string).toContain('- NEW');+ });+ });+describe('modifyNodes - remove then add', () => {it('should remove 13 paragraphs then insert a list', async () => {// Initialize editor with the JSON fixturediff --git a/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap b/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snapindex 9f5c2f887a0..e0e2c3711e3 100644--- a/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap+++ b/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap@@ -92,18 +92,18 @@ exports[`EditorRuntime - Real Cases > modifyNodes - remove then add > should rem<h2 id="wtm5"><span id="wz6g">必游景点</span></h2>- <ul id="fiv4">- <li id="foff">- <span id="ftzq">西湖风景区:杭州的灵魂,世界文化遗产</span>+ <ul id="9nfi">+ <li id="9szt">+ <span id="9yk4">西湖风景区:杭州的灵魂,世界文化遗产</span></li>- <li id="fzk1">- <span id="g54c">灵隐寺:杭州最著名的佛教寺庙</span>+ <li id="a44f">+ <span id="a9oq">灵隐寺:杭州最著名的佛教寺庙</span></li>- <li id="gaon">- <span id="gg8y">西溪国家湿地公园:中国第一个国家湿地公园</span>+ <li id="af91">+ <span id="aktc">西溪国家湿地公园:中国第一个国家湿地公园</span></li>- <li id="glt9">- <span id="grdk">宋城:以宋代文化为主题的大型主题公园</span>+ <li id="aqdn">+ <span id="avxy">宋城:以宋代文化为主题的大型主题公园</span></li></ul><h2 id="562n">diff --git a/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.tsnew file mode 100644index 00000000000..14158616103--- /dev/null+++ b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { formatModifyNodesResult } from '../formatModifyNodesResult';++describe('formatModifyNodesResult', () => {+ it('summarises a fully applied batch', () => {+ expect(+ formatModifyNodesResult({+ results: [+ { action: 'insert', success: true },+ { action: 'insert', success: true },+ ],+ successCount: 2,+ totalCount: 2,+ }),+ ).toBe('Successfully executed 2 inserts (2/2 operations succeeded).');+ });++ it('does not report a partially applied batch as a success', () => {+ const content = formatModifyNodesResult({+ results: [+ { action: 'modify', error: 'node "zzzz" not found in the document', success: false },+ { action: 'insert', success: true },+ ],+ successCount: 1,+ totalCount: 2,+ });++ expect(content).not.toContain('Successfully');+ expect(content).toMatchInlineSnapshot(`+ "Only 1/2 operations succeeded (1 modify, 1 insert requested). Failed operations were not applied:+ - Operation 1 (modify): node "zzzz" not found in the document+ Call getPageContent to get the current node ids before retrying the failed operations."+ `);+ });+});diff --git a/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts b/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.tsnew file mode 100644index 00000000000..be7513ca037--- /dev/null+++ b/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it } from 'vitest';++import {+ describeLiteXMLEditStep,+ findLiteXMLEditStepProblem,+ indexLiteXMLDocument,+ planLiteXMLEditSteps,+ touchesList,+} from '../liteXMLEditPlan';++describe('liteXMLEditPlan', () => {+ it('indexes ids and marks nodes nested in lists', () => {+ const index = indexLiteXMLDocument(+ '<root><p id="p1"><span id="s1">x</span></p><ul id="u1"><li id="l1"><span id="s2">a</span></li></ul><br/></root>',+ );++ expect([...index.ids]).toEqual(['p1', 's1', 'u1', 'l1', 's2']);+ expect([...index.listIds]).toEqual(['u1', 'l1', 's2']);+ expect(index.ancestorIds.get('s2')).toEqual(['l1', 'u1']);+ expect(touchesList({ action: 'remove', id: 's2' }, index)).toBe(true);+ expect(touchesList({ action: 'remove', id: 's1' }, index)).toBe(false);+ });++ it('scans unterminated tags in linear time', () => {+ const start = performance.now();+ indexLiteXMLDocument(`<p id="a">${'<a '.repeat(50_000)}`);+ expect(performance.now() - start).toBeLessThan(500);+ });++ it('splits a same-anchor insert run where list content starts, applying pieces last-first', () => {+ const empty = indexLiteXMLDocument('<root><p id="x"></p></root>');+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<h3>Title</h3>' },+ { action: 'insert', afterId: 'x', litexml: '<p>Intro</p>' },+ { action: 'insert', afterId: 'x', litexml: '<ul><li>a</li></ul>' },+ { action: 'remove', id: 'x' },+ ],+ empty,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[2], [0, 1], [3]]);+ expect(steps[1].operation).toMatchObject({+ litexml: '<root><h3>Title</h3><p>Intro</p></root>',+ });+ expect(steps.map((step) => touchesList(step.operation, empty))).toEqual([true, false, false]);+ });++ const flat = indexLiteXMLDocument('<root><p id="x">x</p><p id="y">y</p></root>');+ const nested = indexLiteXMLDocument(+ '<root><ul id="l"><li id="x"><span id="s">x</span></li></ul><p id="y">y</p></root>',+ );++ it('groups same-anchor inserts across operations that leave the anchor alone', () => {+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<p>A</p>' },+ { action: 'modify', litexml: '<p id="y">Y</p>' },+ { action: 'insert', afterId: 'x', litexml: '<p>B</p>' },+ ],+ flat,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[0, 2], [1]]);+ expect(steps[0].operation).toMatchObject({ litexml: '<root><p>A</p><p>B</p></root>' });+ expect(describeLiteXMLEditStep(steps[0], 3)).toBe('Operations 1, 3 of 3 (insert)');+ });++ it('stops grouping at an operation that touches the anchor', () => {+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<p>A</p>' },+ { action: 'remove', id: 'x' },+ { action: 'insert', afterId: 'x', litexml: '<p>B</p>' },+ ],+ flat,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[0], [1], [2]]);+ });++ it('stops grouping at an operation that replaces a node enclosing the anchor', () => {+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<li>A</li>' },+ { action: 'modify', litexml: '<ul id="l"><li id="x"><span id="s">x2</span></li></ul>' },+ { action: 'insert', afterId: 'x', litexml: '<li>B</li>' },+ ],+ nested,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[0], [1], [2]]);+ });++ it('still groups past an edit nested inside the anchor', () => {+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<li>A</li>' },+ { action: 'modify', litexml: '<span id="s">x2</span>' },+ { action: 'insert', afterId: 'x', litexml: '<li>B</li>' },+ ],+ nested,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[0, 2], [1]]);+ });++ it('keeps an empty insert out of a merged run so its no-op is reported', () => {+ const steps = planLiteXMLEditSteps(+ [+ { action: 'insert', afterId: 'x', litexml: '<p>A</p>' },+ { action: 'insert', afterId: 'x', litexml: ' ' },+ { action: 'insert', afterId: 'x', litexml: '<p>B</p>' },+ ],+ flat,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[2], [1], [0]]);+ });++ it('splits a modify mixing list and non-list fragments so only the list part skips review', () => {+ const steps = planLiteXMLEditSteps(+ [+ {+ action: 'modify',+ litexml: ['<p id="y">Y2</p>', '<span id="s">x2</span>'],+ },+ ],+ nested,+ );++ expect(steps.map((step) => step.indexes)).toEqual([[0], [0]]);+ expect(steps.map((step) => step.operation)).toEqual([+ { action: 'modify', litexml: ['<p id="y">Y2</p>'] },+ { action: 'modify', litexml: ['<span id="s">x2</span>'] },+ ]);+ expect(steps.map((step) => touchesList(step.operation, nested))).toEqual([false, true]);+ });++ it('rejects a modify whose fragments target a node and one enclosed by it', () => {+ const operation = {+ action: 'modify' as const,+ litexml: [+ '<ul id="l"><li id="x"><span>x2</span></li></ul>',+ '<li id="x"><span>x3</span></li>',+ ],+ };++ expect(findLiteXMLEditStepProblem(operation, nested)).toContain('node "l" encloses node "x"');+ expect(+ findLiteXMLEditStepProblem(+ { action: 'modify', litexml: ['<span id="s">x2</span>', '<ul id="l"></ul>'] },+ nested,+ ),+ ).toContain('node "l" encloses node "s"');+ expect(+ findLiteXMLEditStepProblem(+ { action: 'modify', litexml: ['<p id="y">1</p>', '<p id="y">2</p>'] },+ flat,+ ),+ ).toContain('more than one fragment');+ expect(+ findLiteXMLEditStepProblem(+ { action: 'modify', litexml: ['<p id="x">1</p>', '<p id="y">2</p>'] },+ flat,+ ),+ ).toBeUndefined();+ });++ it('keeps a mixed modify with overlapping targets whole so it fails before any part applies', () => {+ const quoted = indexLiteXMLDocument(+ '<root><blockquote id="q"><ul id="l"><li id="x">x</li></ul></blockquote></root>',+ );+ const operation = {+ action: 'modify' as const,+ litexml: ['<blockquote id="q"><p>q</p></blockquote>', '<li id="x">x2</li>'],+ };+ const steps = planLiteXMLEditSteps([operation], quoted);++ expect(steps.map((step) => step.operation)).toEqual([operation]);+ expect(findLiteXMLEditStepProblem(steps[0].operation, quoted)).toContain(+ 'node "q" encloses node "x"',+ );+ });+});diff --git a/packages/editor-runtime/src/formatModifyNodesResult.ts b/packages/editor-runtime/src/formatModifyNodesResult.tsnew file mode 100644index 00000000000..a8dbf6d505e--- /dev/null+++ b/packages/editor-runtime/src/formatModifyNodesResult.ts@@ -0,0 +1,38 @@+import type { ModifyNodesRuntimeResult } from './types';++/**+ * Tool message for a page-agent `modifyNodes` call. Failed operations are listed+ * with their reason so the model retries them instead of assuming they applied.+ */+export const formatModifyNodesResult = ({+ results,+ successCount,+ totalCount,+}: ModifyNodesRuntimeResult): string => {+ const summary = Object.entries(+ results.reduce<Record<string, number>>((acc, { action }) => {+ acc[action] = (acc[action] || 0) + 1;+ return acc;+ }, {}),+ )+ .map(([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`)+ .join(', ');++ if (successCount === totalCount) {+ return `Successfully executed ${summary} (${successCount}/${totalCount} operations succeeded).`;+ }++ const failures = results+ .map((result, index) =>+ result.success+ ? undefined+ : `- Operation ${index + 1} (${result.action}): ${result.error ?? 'not applied'}`,+ )+ .filter(Boolean);++ return [+ `Only ${successCount}/${totalCount} operations succeeded (${summary} requested). Failed operations were not applied:`,+ ...failures,+ 'Call getPageContent to get the current node ids before retrying the failed operations.',+ ].join('\n');+};diff --git a/packages/editor-runtime/src/index.ts b/packages/editor-runtime/src/index.tsindex 804aa18c8df..907542e5a15 100644--- a/packages/editor-runtime/src/index.ts+++ b/packages/editor-runtime/src/index.ts@@ -1,2 +1,4 @@export { EditorRuntime, type LiteXMLBatchOperation } from './EditorRuntime';+export { formatModifyNodesResult } from './formatModifyNodesResult';+export * from './liteXMLEditPlan';export * from './types';diff --git a/packages/editor-runtime/src/liteXMLEditPlan.ts b/packages/editor-runtime/src/liteXMLEditPlan.tsnew file mode 100644index 00000000000..f93f86e99c1--- /dev/null+++ b/packages/editor-runtime/src/liteXMLEditPlan.ts@@ -0,0 +1,313 @@+import type { ModifyOperation } from './types';++/**+ * Pure planning helpers shared by every LiteXML node-edit path (the page agent's+ * `EditorRuntime` and the server's headless agent-document editor). They decide+ * the order operations run in, which ids each one needs, and whether it can be+ * applied as a pending review diff.+ */++export const normalizeLiteXMLFragment = (litexml: string) => {+ const trimmed = litexml.trim();++ return trimmed.startsWith('<root>') ? trimmed : `<root>${trimmed}</root>`;+};++const stripRootElement = (litexml: string) => {+ const trimmed = litexml.trim();++ return trimmed.startsWith('<root>') && trimmed.endsWith('</root>')+ ? trimmed.slice('<root>'.length, -'</root>'.length)+ : trimmed;+};++// Attributes stop at `<` as well as `>` (LiteXML escapes `<` in values), so an+// unterminated tag cannot make every later match rescan the rest of the input.+const LITEXML_TAG_PATTERN = /<(\/?)([a-z][\w-]*)(\s[^<>]*)?>/gi;+const LITEXML_ID_ATTRIBUTE = /\bid="([^"]+)"/;+const LIST_TAGS = new Set(['li', 'ol', 'ul']);++export interface LiteXMLDocumentIndex {+ /** Ids of the nodes enclosing each node, nearest first. */+ ancestorIds: Map<string, string[]>;+ ids: Set<string>;+ /** Ids of list containers, list items and every node nested inside them. */+ listIds: Set<string>;+}++export const indexLiteXMLDocument = (litexml: string): LiteXMLDocumentIndex => {+ const ancestorIds = new Map<string, string[]>();+ const ids = new Set<string>();+ const listIds = new Set<string>();+ const stack: { id?: string; inList: boolean }[] = [];++ for (const [, closing, tag, attributes = ''] of litexml.matchAll(LITEXML_TAG_PATTERN)) {+ if (closing) {+ stack.pop();+ continue;+ }++ const inList = (stack.at(-1)?.inList ?? false) || LIST_TAGS.has(tag.toLowerCase());+ const id = attributes.match(LITEXML_ID_ATTRIBUTE)?.[1];+ if (id) {+ ids.add(id);+ if (inList) listIds.add(id);+ const ancestors: string[] = [];+ for (let depth = stack.length - 1; depth >= 0; depth -= 1) {+ const ancestorId = stack[depth].id;+ if (ancestorId) ancestors.push(ancestorId);+ }+ ancestorIds.set(id, ancestors);+ }+ if (!attributes.endsWith('/')) stack.push({ id, inList });+ }++ return { ancestorIds, ids, listIds };+};++/** Ids carried by the top-level nodes of a `modify` payload — the nodes it replaces. */+const getTopLevelLiteXMLIds = (litexml: string): (string | undefined)[] => {+ const ids: (string | undefined)[] = [];+ let depth = 0;++ for (const [, closing, tag, attributes = ''] of normalizeLiteXMLFragment(litexml).matchAll(+ LITEXML_TAG_PATTERN,+ )) {+ if (closing) {+ depth -= 1;+ continue;+ }+ if (depth === 1 && tag !== 'root') ids.push(attributes.match(LITEXML_ID_ATTRIBUTE)?.[1]);+ if (!attributes.endsWith('/')) depth += 1;+ }++ return ids;+};++const toFragments = (litexml: string | string[]) => (Array.isArray(litexml) ? litexml : [litexml]);++/**+ * Ids an operation targets. `undefined` marks a top-level node of a `modify`+ * payload without an id — the editor cannot tell which node it should replace.+ */+export const getReferencedIds = (operation: ModifyOperation): (string | undefined)[] => {+ switch (operation.action) {+ case 'insert': {+ const anchor = 'beforeId' in operation ? operation.beforeId : operation.afterId;+ return anchor === 'root' ? [] : [anchor];+ }+ case 'modify': {+ return toFragments(operation.litexml).flatMap(getTopLevelLiteXMLIds);+ }+ case 'remove': {+ return [operation.id];+ }+ }+};++const LIST_MARKUP_PATTERN = /<(?:li|ol|ul)[\s/>]/i;++const fragmentTouchesList = (litexml: string, document: LiteXMLDocumentIndex) =>+ LIST_MARKUP_PATTERN.test(litexml) ||+ getTopLevelLiteXMLIds(litexml).some((id) => id !== undefined && document.listIds.has(id));++/**+ * Pending review diffs (`delay: true`) are not safe for lists in @lobehub/editor:+ * list-item add/remove diffs serialize as empty items, a whole-list modify drops+ * the list, and an inserted list becomes a code block. Edits that touch a list+ * must be applied directly; every other edit can keep the review diff.+ */+export const touchesList = (operation: ModifyOperation, document: LiteXMLDocumentIndex) => {+ if (getReferencedIds(operation).some((id) => id !== undefined && document.listIds.has(id))) {+ return true;+ }+ if (operation.action === 'remove') return false;++ return toFragments(operation.litexml).some((litexml) => LIST_MARKUP_PATTERN.test(litexml));+};++export interface LiteXMLEditStep {+ /** Positions of the caller's operations this step applies. */+ indexes: number[];+ operation: ModifyOperation;+}++type AfterInsertOperation = Extract<ModifyOperation, { afterId: string }>;++const isAfterInsert = (operation: ModifyOperation): operation is AfterInsertOperation =>+ operation.action === 'insert' && 'afterId' in operation;++const hasListMarkup = (operation: ModifyOperation) =>+ operation.action !== 'remove' &&+ toFragments(operation.litexml).some((litexml) => LIST_MARKUP_PATTERN.test(litexml));++/** An insert with nothing to insert; kept on its own so its no-op is reported. */+const isEmptyInsert = (operation: AfterInsertOperation) =>+ stripRootElement(operation.litexml).trim().length === 0;++/**+ * Whether `operation` can remove or replace `anchorId`: it targets the anchor+ * itself, one of the nodes enclosing it, or a node it cannot identify.+ */+const affectsAnchor = (+ operation: ModifyOperation,+ anchorId: string,+ document: LiteXMLDocumentIndex,+) => {+ const scope = new Set([anchorId, ...(document.ancestorIds.get(anchorId) ?? [])]);++ return getReferencedIds(operation).some((id) => id === undefined || scope.has(id));+};++/**+ * A pair of targets in one `modify` where the first is the second or encloses+ * it. Replacing the outer node re-keys or drops the inner one, so the inner+ * fragment would be lost while the outer change makes the step look applied.+ */+const findOverlappingModifyTargets = (+ operation: ModifyOperation,+ document: LiteXMLDocumentIndex,+): [outer: string, inner: string] | undefined => {+ if (operation.action !== 'modify') return undefined;++ const targets = getReferencedIds(operation).filter((id): id is string => id !== undefined);+ for (const [position, inner] of targets.entries()) {+ const scope = new Set([inner, ...(document.ancestorIds.get(inner) ?? [])]);+ const outer = targets.find((id, other) => other !== position && scope.has(id));+ if (outer) return [outer, inner];+ }++ return undefined;+};++/**+ * A `modify` whose fragments mix list and non-list nodes is split into one step+ * per kind, so only the list fragments skip the review diff. One with+ * overlapping targets stays whole so it is rejected before any part applies.+ */+const splitModifyByList = (+ operation: Extract<ModifyOperation, { action: 'modify' }>,+ document: LiteXMLDocumentIndex,+): ModifyOperation[] => {+ if (!Array.isArray(operation.litexml)) return [operation];+ if (findOverlappingModifyTargets(operation, document)) return [operation];++ const list = operation.litexml.filter((litexml) => fragmentTouchesList(litexml, document));+ const other = operation.litexml.filter((litexml) => !fragmentTouchesList(litexml, document));+ if (list.length === 0 || other.length === 0) return [operation];++ return [+ { ...operation, litexml: other },+ { ...operation, litexml: list },+ ];+};++/**+ * Keep the caller's order. Inserts after the same anchor are merged: applied one+ * by one, each would land directly after the anchor and the batch would come out+ * reversed. The merge reaches past operations in between as long as they leave+ * the anchor alone; one that removes or replaces the anchor or a node enclosing+ * it ends it. A run mixing list and non-list content is split where that+ * changes, so only the list part skips the review diff; the pieces are then+ * applied last-first, each landing after the anchor ahead of the previous piece.+ * An empty insert stays a piece of its own so its no-op fails instead of riding+ * on a neighbour's change.+ *+ * `document` is the LiteXML index of the document before any operation runs.+ */+export const planLiteXMLEditSteps = (+ operations: ModifyOperation[],+ document: LiteXMLDocumentIndex,+): LiteXMLEditStep[] => {+ const steps: LiteXMLEditStep[] = [];+ const merged = new Set<number>();++ operations.forEach((operation, index) => {+ if (merged.has(index)) return;+ if (operation.action === 'modify') {+ for (const part of splitModifyByList(operation, document)) {+ steps.push({ indexes: [index], operation: part });+ }+ return;+ }+ if (!isAfterInsert(operation)) {+ steps.push({ indexes: [index], operation });+ return;+ }++ const pieces: (LiteXMLEditStep & { operation: AfterInsertOperation })[] = [];+ for (let nextIndex = index; nextIndex < operations.length; nextIndex += 1) {+ if (merged.has(nextIndex)) continue;++ const next = operations[nextIndex];+ if (!isAfterInsert(next) || next.afterId !== operation.afterId) {+ if (affectsAnchor(next, operation.afterId, document)) break;+ continue;+ }+ merged.add(nextIndex);++ const piece = pieces.at(-1);+ if (+ piece &&+ !isEmptyInsert(piece.operation) &&+ !isEmptyInsert(next) &&+ hasListMarkup(piece.operation) === hasListMarkup(next)+ ) {+ piece.indexes.push(nextIndex);+ piece.operation = {+ ...next,+ litexml: `<root>${stripRootElement(piece.operation.litexml)}${stripRootElement(next.litexml)}</root>`,+ };+ } else {+ pieces.push({ indexes: [nextIndex], operation: next });+ }+ }++ steps.push(...pieces.reverse());+ });++ return steps;+};++export const describeLiteXMLEditStep = ({ indexes, operation }: LiteXMLEditStep, total: number) => {+ const first = indexes[0] + 1;+ const last = indexes.at(-1)! + 1;+ const positions =+ indexes.length === 1+ ? `Operation ${first}`+ : last - first === indexes.length - 1+ ? `Operations ${first}-${last}`+ : `Operations ${indexes.map((index) => index + 1).join(', ')}`;++ return `${positions} of ${total} (${operation.action})`;+};++/**+ * Why a step cannot run against the current document, or `undefined` when every+ * id it needs is present.+ */+export const findLiteXMLEditStepProblem = (+ operation: ModifyOperation,+ document: LiteXMLDocumentIndex,+): string | undefined => {+ const referencedIds = getReferencedIds(operation);++ if (referencedIds.includes(undefined)) {+ return 'every top-level node in a modify payload needs the id of the node it replaces';+ }++ const missingIds = (referencedIds as string[]).filter((id) => !document.ids.has(id));+ if (missingIds.length > 0) {+ return `node ${missingIds.map((id) => `"${id}"`).join(', ')} not found in the document`;+ }++ const overlap = findOverlappingModifyTargets(operation, document);+ if (overlap) {+ const [outer, inner] = overlap;+ return outer === inner+ ? `node "${outer}" is targeted by more than one fragment; send one fragment per node`+ : `node "${outer}" encloses node "${inner}", so replacing it would discard the edit to "${inner}"; put the change to "${inner}" inside the "${outer}" fragment instead`;+ }++ return undefined;+};diff --git a/src/utils/__tests__/agentDocumentContextMapping.test.ts b/src/utils/__tests__/agentDocumentContextMapping.test.tsindex 0edc83f6f4c..e53265e8685 100644--- a/src/utils/__tests__/agentDocumentContextMapping.test.ts+++ b/src/utils/__tests__/agentDocumentContextMapping.test.ts@@ -73,6 +73,11 @@ describe('toAgentContextDocument', () => {expect(toAgentContextDocument(buildDoc({ updatedAt: ts })).updatedAt).toBe(ts);});+ it('propagates createdAt so the index can mark docs created during the current run', () => {+ const ts = new Date('2026-09-23T22:57:58.000Z');+ expect(toAgentContextDocument(buildDoc({ createdAt: ts })).createdAt).toBe(ts);+ });+it('maps a fully populated row into the AgentContextDocument shape', () => {const doc = buildDoc({description: 'web-crawled article',@@ -91,6 +96,7 @@ describe('toAgentContextDocument', () => {expect(toAgentContextDocument(doc)).toEqual({content: 'body',contentCharCount: 4,+ createdAt: doc.createdAt,description: 'web-crawled article',filename: 'crawl.md',id: 'agent-doc-2',diff --git a/src/utils/agentDocumentContextMapping.ts b/src/utils/agentDocumentContextMapping.tsindex 93ffcb20caf..560377f2987 100644--- a/src/utils/agentDocumentContextMapping.ts+++ b/src/utils/agentDocumentContextMapping.ts@@ -35,6 +35,7 @@ export const normalizeAgentDocumentPosition = (export const toAgentContextDocument = (doc: AgentDocumentContextPayload): AgentContextDocument => ({content: doc.content,contentCharCount: doc.contentCharCount ?? doc.content.length,+ createdAt: doc.createdAt ?? undefined,description: doc.description ?? undefined,filename: doc.filename,id: doc.id,