Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-documents): keep modifyNodes node ids addressable after a write (#20409)

Arvin Xu5b4850a41345
diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.ts
index 88baea5c4a1..2ff2d34fbd0 100644
--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts
+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts
@@ -73,12 +73,12 @@ describe('agent document headless editor', () => {
});
});
- it('should apply LiteXML operations and persist diff nodes for later human review', async () => {
+ it('should keep a review diff for a replaced top-level block', async () => {
const initial = await exportEditorDataSnapshot({
fallbackContent: 'Original',
litexml: true,
});
- const textId = getSpanId(initial.litexml!, 'Original');
+ const blockId = initial.litexml!.match(/<p id="(\w+)">/)![1];
const snapshot = await applyLiteXMLOperations({
editorData: initial.editorData,
@@ -86,7 +86,7 @@ describe('agent document headless editor', () => {
operations: [
{
action: 'modify',
- litexml: `<span id="${textId}">Updated</span>`,
+ litexml: `<p id="${blockId}"><span>Updated</span></p>`,
},
],
});
@@ -102,6 +102,25 @@ describe('agent document headless editor', () => {
expect(hasNodeType(snapshot.editorData, 'diff')).toBe(true);
});
+ it('should apply an inline edit directly so the block keeps its id', async () => {
+ const initial = await exportEditorDataSnapshot({
+ fallbackContent: 'Original',
+ litexml: true,
+ });
+ const blockId = initial.litexml!.match(/<p id="(\w+)">/)![1];
+ const textId = getSpanId(initial.litexml!, 'Original');
+
+ const snapshot = await applyLiteXMLOperations({
+ editorData: initial.editorData,
+ fallbackContent: initial.content,
+ operations: [{ action: 'modify', litexml: `<span id="${textId}">Updated</span>` }],
+ });
+
+ expect(snapshot.content).toBe('Updated\n');
+ expect(snapshot.litexml).toContain(`<p id="${blockId}">`);
+ expect(hasNodeType(snapshot.editorData, 'diff')).toBe(false);
+ });
+
it('should fall back to Markdown when valid editor data hydrates to an empty document', async () => {
const empty = await createMarkdownEditorSnapshot('');
diff --git a/apps/server/src/services/agentDocuments/headlessEditor.ts b/apps/server/src/services/agentDocuments/headlessEditor.ts
index 05a125d9195..45a4895a172 100644
--- a/apps/server/src/services/agentDocuments/headlessEditor.ts
+++ b/apps/server/src/services/agentDocuments/headlessEditor.ts
@@ -1,10 +1,10 @@
import {
+ canApplyAsReviewDiff,
describeLiteXMLEditStep,
findLiteXMLEditStepProblem,
indexLiteXMLDocument,
normalizeLiteXMLFragment,
planLiteXMLEditSteps,
- touchesList,
} from '@lobechat/editor-runtime';
import type { HeadlessEditorOptions, HeadlessLiteXMLOperation } from '@lobehub/editor/headless';
import { createHeadlessEditor, DEFAULT_HEADLESS_EDITOR_PLUGINS } from '@lobehub/editor/headless';
@@ -290,7 +290,7 @@ export const applyLiteXMLOperations = async ({
if (problem) throw new Error(`${label} failed: ${problem}. ${NOTHING_SAVED_HINT}`);
await editor.applyLiteXML(
- toHeadlessLiteXMLOperation(operation, !touchesList(operation, document)),
+ toHeadlessLiteXMLOperation(operation, canApplyAsReviewDiff(operation, document)),
);
const next = exportSnapshot(editor, true);
diff --git a/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts b/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts
index 102980b991e..b33b9cc6688 100644
--- a/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts
+++ b/apps/server/src/services/agentDocuments/modifyNodes.regression.test.ts
@@ -1,6 +1,7 @@
// @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 { createHeadlessEditor } from '@lobehub/editor/headless';
import { describe, expect, it } from 'vitest';
import type { AgentDocumentLiteXMLOperation } from './headlessEditor';
@@ -227,10 +228,9 @@ describe('agent document markdown writes regressions', () => {
).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 () => {
+ // Table edits used to be stored as a pending review diff, and the cell diff
+ // broke the column layout; they are now applied directly.
+ it('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, [
@@ -239,4 +239,113 @@ describe('agent document markdown writes regressions', () => {
const header = back.content.split('\n')[0];
expect(header.split('|').length - 2).toBe(3);
});
+
+ describe('node ids stay addressable after a write', () => {
+ const DOC =
+ '# T\n\n## Section\n\nversion **v1** and note\n\n| a | b |\n| - | - |\n| 1 | 2 |\n| 3 | 4 |\n\ntail\n';
+ const spanId = (xml: string, text: string) =>
+ xml.match(new RegExp(`<span id="(\\w+)"[^>]*>${text}</span>`))![1];
+ const rowId = (xml: string, text: string) =>
+ xml.match(
+ new RegExp(`<tr id="(\\w+)">\\s*<td id="\\w+">\\s*<span id="\\w+">${text}</span>`),
+ )![1];
+ const parentId = (xml: string, tag: string, text: string) =>
+ xml.match(new RegExp(`<${tag} id="(\\w+)">(?:(?!</${tag}>)[\\s\\S])*>${text}</span>`))![1];
+
+ it('R12 modifying a span keeps the ids of its block and siblings for the next call', async () => {
+ const base = await load(DOC);
+ const x = base.litexml!;
+ const block = parentId(x, 'p', 'v1');
+ const sibling = spanId(x, ' and note');
+ const after = await editThenRead(base, [
+ { action: 'modify', litexml: `<span id="${spanId(x, 'v1')}" bold="true">v2</span>` },
+ ]);
+
+ // A later call still built from the first read's ids.
+ const back = await editThenRead(after, [
+ { action: 'modify', litexml: `<span id="${sibling}"> and a new note</span>` },
+ { action: 'insert', afterId: block, litexml: '<p><span>appended</span></p>' },
+ ]);
+ expect(back.content).toContain('version **v2** and a new note');
+ expect(back.content).toContain('appended');
+ });
+
+ it('R13 a modify inside a heading does not break a later insert anchored on it in the same batch', async () => {
+ const base = await load(DOC);
+ const x = base.litexml!;
+ const heading = parentId(x, 'h2', 'Section');
+ const back = await editThenRead(base, [
+ { action: 'modify', litexml: `<span id="${spanId(x, 'Section')}">Renamed</span>` },
+ { action: 'insert', beforeId: heading, litexml: '<p><span>before heading</span></p>' },
+ ]);
+ expect(back.content).toContain('before heading\n\n## Renamed');
+ });
+
+ it('R14 table rows created by insert can be modified, removed and anchored on later', async () => {
+ const base = await load(DOC);
+ const inserted = await editThenRead(base, [
+ {
+ action: 'insert',
+ afterId: rowId(base.litexml!, '1'),
+ litexml: '<tr><td><span>9 pass</span></td><td><span>x</span></td></tr>',
+ },
+ ]);
+ const x = inserted.litexml!;
+
+ const modified = await editThenRead(inserted, [
+ { action: 'modify', litexml: `<span id="${spanId(x, '9 pass')}">12 pass</span>` },
+ ]);
+ expect(modified.content).toMatch(/\| 12 pass \| x +\|/);
+
+ const anchored = await editThenRead(inserted, [
+ {
+ action: 'insert',
+ afterId: rowId(x, '9 pass'),
+ litexml: '<tr><td><span>z</span></td><td><span>z</span></td></tr>',
+ },
+ ]);
+ expect(anchored.content).toMatch(/9 pass[^\n]*\n\| z/);
+
+ const removed = await editThenRead(inserted, [{ action: 'remove', id: rowId(x, '9 pass') }]);
+ expect(removed.content).not.toContain('9 pass');
+ });
+
+ it('R15 editing a cell keeps the row shape', async () => {
+ const base = await load(DOC);
+ const back = await editThenRead(base, [
+ { action: 'modify', litexml: `<span id="${spanId(base.litexml!, '3')}">33</span>` },
+ ]);
+ expect(back.content).toMatch(/\| 33 +\| 4 +\|/);
+ });
+
+ it('R16 rows stored as a pending review diff by earlier writes can still be edited', async () => {
+ const base = await load(DOC);
+ // Documents written before this fix hold inserted rows as `table-row-diff`.
+ const editor = createHeadlessEditor();
+ editor.hydrateEditorData(base.editorData as any, { keepId: true });
+ await editor.applyLiteXML({
+ action: 'insert',
+ afterId: rowId(base.litexml!, '1'),
+ delay: true,
+ litexml: '<root><tr><td><span>9 pass</span></td><td><span>x</span></td></tr></root>',
+ });
+ const legacy = editor.export({ litexml: true });
+ editor.destroy();
+ expect(JSON.stringify(legacy.editorData)).toContain('table-row-diff');
+
+ const stored = await exportEditorDataSnapshot({
+ editorData: legacy.editorData as any,
+ fallbackContent: legacy.markdown,
+ litexml: true,
+ });
+ const x = stored.litexml!;
+ const modified = await editThenRead(stored, [
+ { action: 'modify', litexml: `<span id="${spanId(x, '9 pass')}">12 pass</span>` },
+ ]);
+ expect(modified.content).toContain('12 pass');
+
+ const removed = await editThenRead(stored, [{ action: 'remove', id: rowId(x, '9 pass') }]);
+ expect(removed.content).not.toContain('9 pass');
+ });
+ });
});
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
index bc9487c72ca..47cf30686d8 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -512,4 +512,65 @@ describe('AgentDocumentsExecutionRuntime', () => {
expect.not.objectContaining({ limit: expect.anything() }),
);
});
+
+ describe('modifyNodes operation shapes', () => {
+ const existing = { documentId: 'docs_1', id: 'agent-doc-1', title: 'Doc' };
+ const setup = () => {
+ const modifyNodes = vi.fn().mockResolvedValue(existing);
+ const runtime = createRuntime({
+ modifyNodes,
+ readDocument: vi.fn().mockResolvedValue(existing),
+ });
+ return { modifyNodes, runtime };
+ };
+
+ it('infers the action and accepts type/content aliases and a JSON-string array', async () => {
+ const { modifyNodes, runtime } = setup();
+
+ const result = await runtime.modifyNodes(
+ {
+ id: 'agent-doc-1',
+ operations: JSON.stringify([
+ { beforeId: 'y0a9', litexml: '<h2><span>a</span></h2>' },
+ { afterId: 'y0a9', litexml: '<h2><span>b</span></h2>' },
+ { litexml: '<span id="ybev">c</span>' },
+ { content: '<p><span>d</span></p>', type: 'insert', afterId: 'y0a9' },
+ { id: 'old1' },
+ ]) as any,
+ },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(modifyNodes.mock.calls[0][0].operations).toEqual([
+ { action: 'insert', beforeId: 'y0a9', litexml: '<h2><span>a</span></h2>' },
+ { action: 'insert', afterId: 'y0a9', litexml: '<h2><span>b</span></h2>' },
+ { action: 'modify', litexml: '<span id="ybev">c</span>' },
+ { action: 'insert', afterId: 'y0a9', litexml: '<p><span>d</span></p>' },
+ { action: 'remove', id: 'old1' },
+ ]);
+ });
+
+ it('rejects an operation it cannot interpret with its position and the expected shapes', async () => {
+ const { modifyNodes, runtime } = setup();
+
+ const result = await runtime.modifyNodes(
+ {
+ id: 'agent-doc-1',
+ operations: [
+ { action: 'remove', id: 'a' },
+ { action: 'replace', litexml: '<p/>' },
+ ] as any,
+ },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain(
+ 'Operation 2 of 2 is not a valid operation; nothing was saved.',
+ );
+ expect(result.content).toContain('{"action":"remove","id":"<node id>"}');
+ expect(modifyNodes).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index bfed59b7346..ed6cd51c5b4 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -15,6 +15,7 @@ import type {
CreateDocumentArgs,
ListDocumentsArgs,
ModifyDocumentNodesArgs,
+ ModifyDocumentOperation,
ReadDocumentArgs,
RemoveDocumentArgs,
RenameDocumentArgs,
@@ -206,6 +207,83 @@ const resolveTargetId = <T extends { id: string }>(
};
};
+const MODIFY_OPERATION_SHAPES =
+ '{"action":"insert","afterId"|"beforeId":"<node id>","litexml":"…"}, {"action":"modify","litexml":"<tag id=\\"<node id>\\">…</tag>"} or {"action":"remove","id":"<node id>"}';
+
+const nonEmptyString = (value: unknown): value is string =>
+ typeof value === 'string' && value.trim().length > 0;
+
+/**
+ * Models send modifyNodes operations in several near-miss shapes: the array as a
+ * JSON string, `type` instead of `action`, `content` instead of `litexml`, or no
+ * `action` at all. Accept the unambiguous ones and reject the rest with the
+ * position and the expected shapes, instead of crashing on a missing `action`.
+ */
+const normalizeModifyOperations = (
+ raw: unknown,
+): { operations: ModifyDocumentOperation[] } | { error: string } => {
+ let list = raw;
+ if (typeof list === 'string') {
+ try {
+ list = JSON.parse(list);
+ } catch {
+ return {
+ error: `\`operations\` must be an array of operations: ${MODIFY_OPERATION_SHAPES}.`,
+ };
+ }
+ }
+ if (!Array.isArray(list) || list.length === 0) return { error: 'No operations provided.' };
+
+ const operations: ModifyDocumentOperation[] = [];
+ for (const [index, item] of list.entries()) {
+ const op = (item ?? {}) as Record<string, unknown>;
+ const litexml = op.litexml ?? op.content;
+ const declared = op.action ?? op.type;
+ const action =
+ declared ??
+ (nonEmptyString(op.afterId) || nonEmptyString(op.beforeId)
+ ? 'insert'
+ : litexml !== undefined
+ ? 'modify'
+ : nonEmptyString(op.id)
+ ? 'remove'
+ : undefined);
+ const invalid = `Operation ${index + 1} of ${list.length} is not a valid operation; nothing was saved. Use ${MODIFY_OPERATION_SHAPES}.`;
+
+ switch (action) {
+ case 'insert': {
+ if (!nonEmptyString(litexml)) return { error: invalid };
+ if (nonEmptyString(op.beforeId)) {
+ operations.push({ action: 'insert', beforeId: op.beforeId, litexml });
+ } else if (nonEmptyString(op.afterId)) {
+ operations.push({ action: 'insert', afterId: op.afterId, litexml });
+ } else {
+ return { error: invalid };
+ }
+ break;
+ }
+ case 'modify': {
+ const valid =
+ nonEmptyString(litexml) ||
+ (Array.isArray(litexml) && litexml.length > 0 && litexml.every(nonEmptyString));
+ if (!valid) return { error: invalid };
+ operations.push({ action: 'modify', litexml: litexml as string | string[] });
+ break;
+ }
+ case 'remove': {
+ if (!nonEmptyString(op.id)) return { error: invalid };
+ operations.push({ action: 'remove', id: op.id });
+ break;
+ }
+ default: {
+ return { error: invalid };
+ }
+ }
+ }
+
+ return { operations };
+};
+
export class AgentDocumentsExecutionRuntime {
constructor(
private service: AgentDocumentsRuntimeService,
@@ -580,10 +658,9 @@ export class AgentDocumentsExecutionRuntime {
return this.buildCurrentPageDocumentWriteBlockedResult('modifyNodes');
}
- const operations = Array.isArray(args.operations) ? args.operations : [];
- if (operations.length === 0) {
- return { content: 'No operations provided.', success: false };
- }
+ const normalized = normalizeModifyOperations(args.operations);
+ if ('error' in normalized) return { content: normalized.error, success: false };
+ const { operations } = normalized;
const updated = await this.service.modifyNodes({
agentId,
diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.ts
index c795e640680..fdd24deb76e 100644
--- a/packages/builtin-tool-agent-documents/src/systemRole.ts
+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts
@@ -33,7 +33,7 @@ Only use listDocuments/readDocument when the user is asking about agent document
- Do not create or maintain managed skills directly; Agent Signal decides whether hinted documents become skills.
- **listDocuments**: list agent documents. Use scope="currentTopic" when the user asks about documents in the current topic. The default agent_documents_index hides web-crawled documents; pass sourceType="web" here to enumerate them, or sourceType="all" to see everything. The index also collapses folders into a single πŸ“ row β€” pass parentId=<folder id from that row> to expand a folder and see its documents. Use this to resolve a title to a document ID before reading. For read and mutation calls, pass the result's \`id\`. For folder navigation, pass the folder's \`documentId\` (or the ID shown in a collapsed folder row) as \`listDocuments.parentId\`.
- **readDocument**: retrieve current content by agent document ID. Pass the \`id\` field returned by listDocuments, not \`documentId\`. This is the only way to read an agent document β€” there is no read-by-filename variant. Prefer format="xml" when you may edit content, because XML includes stable node IDs. If the response contains empty content, the document is genuinely empty; do not retry with a different format or filename.
-- **modifyNodes**: preferred content-edit API. Use LiteXML insert/modify/remove operations after reading XML. For modify operations, include the existing node ID in the LiteXML.
+- **modifyNodes**: preferred content-edit API. Use LiteXML insert/modify/remove operations after reading XML. For modify operations, include the existing node ID in the LiteXML and keep its tag (a <span> id stays a <span>, an <li> id stays an <li>). A modify gives the replaced node a new id and inserts create new nodes; every other node keeps its id, so readDocument again only when you need to address a node you just replaced or inserted.
- **replaceDocumentContent**: overwrite the full content of an existing document only when replacing most or all content.
- **removeDocument**: permanently remove a document by ID.
- **renameDocument**: change document title only.
diff --git a/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts b/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts
index be7513ca037..ff416331878 100644
--- a/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts
+++ b/packages/editor-runtime/src/__tests__/liteXMLEditPlan.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ canApplyAsReviewDiff,
describeLiteXMLEditStep,
findLiteXMLEditStepProblem,
indexLiteXMLDocument,
@@ -182,4 +183,86 @@ describe('liteXMLEditPlan', () => {
'node "q" encloses node "x"',
);
});
+
+ describe('canApplyAsReviewDiff', () => {
+ const doc = indexLiteXMLDocument(
+ '<root><h2 id="h"><span id="hs">Title</span></h2><p id="p"><span id="ps">a</span></p><table id="t"><tr id="r"><td id="c"><span id="cs">1</span></td></tr></table><ul id="u"><li id="l"><span id="ls">x</span></li></ul></root>',
+ );
+
+ it('keeps the review diff for whole top-level blocks', () => {
+ expect(
+ canApplyAsReviewDiff({ action: 'modify', litexml: '<p id="p"><span>b</span></p>' }, doc),
+ ).toBe(true);
+ expect(
+ canApplyAsReviewDiff(
+ { action: 'insert', afterId: 'p', litexml: '<p><span>n</span></p>' },
+ doc,
+ ),
+ ).toBe(true);
+ expect(canApplyAsReviewDiff({ action: 'remove', id: 'h' }, doc)).toBe(true);
+ });
+
+ // A review diff around a nested node re-keys its block (inline) or nests a
+ // diff the editor later rejects (tables), so those apply directly.
+ it('applies nested, table and list edits directly', () => {
+ expect(
+ canApplyAsReviewDiff({ action: 'modify', litexml: '<span id="hs">T</span>' }, doc),
+ ).toBe(false);
+ expect(canApplyAsReviewDiff({ action: 'remove', id: 'ps' }, doc)).toBe(false);
+ expect(
+ canApplyAsReviewDiff(
+ { action: 'insert', afterId: 'r', litexml: '<tr><td><span>2</span></td></tr>' },
+ doc,
+ ),
+ ).toBe(false);
+ expect(
+ canApplyAsReviewDiff(
+ {
+ action: 'insert',
+ afterId: 'p',
+ litexml: '<table><tr><td><span>2</span></td></tr></table>',
+ },
+ doc,
+ ),
+ ).toBe(false);
+ expect(
+ canApplyAsReviewDiff({ action: 'modify', litexml: '<span id="ls">y</span>' }, doc),
+ ).toBe(false);
+ });
+ });
+
+ describe('findLiteXMLEditStepProblem payload checks', () => {
+ const doc = indexLiteXMLDocument(
+ '<root><p id="p"><span id="ps">a</span></p><ul id="u"><li id="l"><span id="ls">x</span></li></ul></root>',
+ );
+
+ it('names an operation without a valid action instead of throwing', () => {
+ expect(
+ findLiteXMLEditStepProblem({ beforeId: 'p', litexml: '<p><span>n</span></p>' } as any, doc),
+ ).toBe('`action` must be "insert", "modify" or "remove"');
+ });
+
+ it('rejects litexml whose tags do not balance', () => {
+ expect(
+ findLiteXMLEditStepProblem(
+ { action: 'insert', afterId: 'p', litexml: '<p><span>A.</span> text</span></p>' },
+ doc,
+ ),
+ ).toBe('the litexml is not well-formed (<p> is closed by </span>)');
+ });
+
+ it('rejects a modify that swaps a list item or span for another kind of node', () => {
+ expect(
+ findLiteXMLEditStepProblem({ action: 'modify', litexml: '<span id="l">y</span>' }, doc),
+ ).toBe(
+ 'node "l" is a <li>, but the modify payload replaces it with a <span>; send a <li id="l"> fragment',
+ );
+ expect(
+ findLiteXMLEditStepProblem(
+ { action: 'modify', litexml: '<h2 id="p"><span>t</span></h2>' },
+ doc,
+ ),
+ ).toBeUndefined();
+ });
+ });
});
diff --git a/packages/editor-runtime/src/liteXMLEditPlan.ts b/packages/editor-runtime/src/liteXMLEditPlan.ts
index f93f86e99c1..ef060cd9b1c 100644
--- a/packages/editor-runtime/src/liteXMLEditPlan.ts
+++ b/packages/editor-runtime/src/liteXMLEditPlan.ts
@@ -33,12 +33,15 @@ export interface LiteXMLDocumentIndex {
ids: Set<string>;
/** Ids of list containers, list items and every node nested inside them. */
listIds: Set<string>;
+ /** Tag name of every node with an id. */
+ tags: Map<string, string>;
}
export const indexLiteXMLDocument = (litexml: string): LiteXMLDocumentIndex => {
const ancestorIds = new Map<string, string[]>();
const ids = new Set<string>();
const listIds = new Set<string>();
+ const tags = new Map<string, string>();
const stack: { id?: string; inList: boolean }[] = [];
for (const [, closing, tag, attributes = ''] of litexml.matchAll(LITEXML_TAG_PATTERN)) {
@@ -51,6 +54,7 @@ export const indexLiteXMLDocument = (litexml: string): LiteXMLDocumentIndex => {
const id = attributes.match(LITEXML_ID_ATTRIBUTE)?.[1];
if (id) {
ids.add(id);
+ tags.set(id, tag.toLowerCase());
if (inList) listIds.add(id);
const ancestors: string[] = [];
for (let depth = stack.length - 1; depth >= 0; depth -= 1) {
@@ -62,9 +66,57 @@ export const indexLiteXMLDocument = (litexml: string): LiteXMLDocumentIndex => {
if (!attributes.endsWith('/')) stack.push({ id, inList });
}
- return { ancestorIds, ids, listIds };
+ return { ancestorIds, ids, listIds, tags };
};
+/** Tag name and id of each top-level node of a fragment. */
+const getTopLevelLiteXMLNodes = (litexml: string): { id?: string; tag: string }[] => {
+ const nodes: { id?: string; tag: string }[] = [];
+ 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') {
+ nodes.push({ id: attributes.match(LITEXML_ID_ATTRIBUTE)?.[1], tag: tag.toLowerCase() });
+ }
+ if (!attributes.endsWith('/')) depth += 1;
+ }
+
+ return nodes;
+};
+
+/** The first closing tag that does not match the open element, if any. */
+const findUnbalancedTag = (litexml: string): string | undefined => {
+ const stack: string[] = [];
+
+ for (const [, closing, tag, attributes = ''] of normalizeLiteXMLFragment(litexml).matchAll(
+ LITEXML_TAG_PATTERN,
+ )) {
+ const name = tag.toLowerCase();
+ if (!closing) {
+ if (!attributes.endsWith('/')) stack.push(name);
+ continue;
+ }
+ const open = stack.pop();
+ if (open !== name) {
+ return open ? `<${open}> is closed by </${name}>` : `</${name}> has no matching opening tag`;
+ }
+ }
+
+ return stack.length > 0 ? `<${stack.at(-1)}> is never closed` : undefined;
+};
+
+/**
+ * Nodes the editor can only replace with a node of the same kind: an inline span
+ * cannot stand in for a list item or a table cell, and vice versa.
+ */
+const SAME_TAG_ONLY = new Set(['li', 'span', 'td', 'th', 'tr']);
+
/** 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)[] = [];
@@ -126,6 +178,37 @@ export const touchesList = (operation: ModifyOperation, document: LiteXMLDocumen
return toFragments(operation.litexml).some((litexml) => LIST_MARKUP_PATTERN.test(litexml));
};
+const TABLE_MARKUP_PATTERN = /<(?:table|tr|td|th)[\s/>]/i;
+
+/**
+ * Whether the server may apply `operation` as a pending review diff
+ * (`delay: true`) and still keep every node id it exposed addressable.
+ *
+ * @lobehub/editor only keeps ids stable for review diffs around whole top-level
+ * blocks. Anything nested breaks the ids the agent was given:
+ * - replacing or removing an inline node clones its enclosing block into the
+ * diff, so the block and every sibling come back with fresh ids;
+ * - table edits wrap rows in `table-row-diff` nodes, and the editor rejects any
+ * later edit inside them as a nested diff β€” the rows read fine but cannot be
+ * modified or removed;
+ * - lists have the problems described on {@link touchesList}.
+ * Such edits are applied directly instead.
+ */
+export const canApplyAsReviewDiff = (
+ operation: ModifyOperation,
+ document: LiteXMLDocumentIndex,
+) => {
+ if (touchesList(operation, document)) return false;
+
+ const nested = getReferencedIds(operation).some(
+ (id) => id === undefined || (document.ancestorIds.get(id)?.length ?? 0) > 0,
+ );
+ if (nested) return false;
+ if (operation.action === 'remove') return true;
+
+ return !toFragments(operation.litexml).some((litexml) => TABLE_MARKUP_PATTERN.test(litexml));
+};
+
export interface LiteXMLEditStep {
/** Positions of the caller's operations this step applies. */
indexes: number[];
@@ -290,6 +373,17 @@ export const findLiteXMLEditStepProblem = (
operation: ModifyOperation,
document: LiteXMLDocumentIndex,
): string | undefined => {
+ if (!['insert', 'modify', 'remove'].includes(operation.action)) {
+ return '`action` must be "insert", "modify" or "remove"';
+ }
+
+ if (operation.action !== 'remove') {
+ for (const litexml of toFragments(operation.litexml)) {
+ const unbalanced = findUnbalancedTag(litexml);
+ if (unbalanced) return `the litexml is not well-formed (${unbalanced})`;
+ }
+ }
+
const referencedIds = getReferencedIds(operation);
if (referencedIds.includes(undefined)) {
@@ -301,6 +395,15 @@ export const findLiteXMLEditStepProblem = (
return `node ${missingIds.map((id) => `"${id}"`).join(', ')} not found in the document`;
}
+ if (operation.action === 'modify') {
+ for (const { id, tag } of toFragments(operation.litexml).flatMap(getTopLevelLiteXMLNodes)) {
+ const target = id && document.tags.get(id);
+ if (target && target !== tag && (SAME_TAG_ONLY.has(target) || SAME_TAG_ONLY.has(tag))) {
+ return `node "${id}" is a <${target}>, but the modify payload replaces it with a <${tag}>; send a <${target} id="${id}"> fragment`;
+ }
+ }
+ }
+
const overlap = findOverlappingModifyTargets(operation, document);
if (overlap) {
const [outer, inner] = overlap;