π€― 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): explain malformed LiteXML instead of "the editor rejected it" (#20410)
Arvin Xu5b0b02b7d7a6
diff --git a/apps/server/src/services/agentDocuments/headlessEditor.test.ts b/apps/server/src/services/agentDocuments/headlessEditor.test.tsindex 2ff2d34fbd0..55776a14fa8 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.test.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.test.ts@@ -208,4 +208,50 @@ describe('agent document headless editor', () => {}),).rejects.toThrow('Operation 1 of 1 (insert) failed: node "missing-node" not found');});++ describe('LiteXML that is not well-formed', () => {+ // Fragment from a real modifyNodes insert that was reported as+ // "the editor rejected it": the text holds a raw `<model>`.+ const fragment =+ '<h2>404 ηε </h2><ol><li>ε‘«ζ https://api.deepseek.com/v1οΌθ―·ζ±ζε° /v1/messagesγ</li><li>lh provider test -m <model> θ½ζβ樑ε ID ζ―ε¦ζζβεζεζ§γ</li></ol>';++ const lastParagraphId = async () => {+ const initial = await exportEditorDataSnapshot({+ fallbackContent: 'first\n\nlast',+ litexml: true,+ });+ const ids = [...initial.litexml!.matchAll(/<p id="([^"]+)"/g)].map((match) => match[1]);++ return { afterId: ids.at(-1)!, initial };+ };++ it('names the unclosed tag and how to escape it instead of "the editor rejected it"', async () => {+ const { afterId, initial } = await lastParagraphId();++ const attempt = applyLiteXMLOperations({+ editorData: initial.editorData,+ operations: [{ action: 'insert', afterId, litexml: fragment }],+ });++ await expect(attempt).rejects.toThrow(+ 'Operation 1 of 1 (insert) failed: litexml is not well-formed XML (<model> is never closed)',+ );+ await expect(attempt).rejects.toThrow('"<"');+ await expect(attempt).rejects.not.toThrow('the editor rejected it');+ });++ it('applies the same fragment once the text escapes "<", bare URL included', async () => {+ const { afterId, initial } = await lastParagraphId();++ const result = await applyLiteXMLOperations({+ editorData: initial.editorData,+ operations: [+ { action: 'insert', afterId, litexml: fragment.replace('<model>', '<model>') },+ ],+ });++ expect(result.content).toContain('https://api.deepseek.com/v1');+ expect(result.content).toContain('<model>');+ });+ });});diff --git a/apps/server/src/services/agentDocuments/headlessEditor.ts b/apps/server/src/services/agentDocuments/headlessEditor.tsindex 45a4895a172..121935ab357 100644--- a/apps/server/src/services/agentDocuments/headlessEditor.ts+++ b/apps/server/src/services/agentDocuments/headlessEditor.ts@@ -2,6 +2,7 @@ import {canApplyAsReviewDiff,describeLiteXMLEditStep,findLiteXMLEditStepProblem,+ findMalformedLiteXML,indexLiteXMLDocument,normalizeLiteXMLFragment,planLiteXMLEditSteps,@@ -286,6 +287,13 @@ export const applyLiteXMLOperations = async ({const label = describeLiteXMLEditStep(step, operations.length);const document = indexLiteXMLDocument(current.litexml ?? '');+ const malformed = 'litexml' in operation && findMalformedLiteXML(operation.litexml);+ if (malformed) {+ throw new Error(+ `${label} failed: ${malformed}. No operations were saved; fix the litexml and retry the whole batch.`,+ );+ }+const problem = findLiteXMLEditStepProblem(operation, document);if (problem) throw new Error(`${label} failed: ${problem}. ${NOTHING_SAVED_HINT}`);diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex 2704241d16e..59341814be3 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -16,6 +16,7 @@ import {planLiteXMLEditSteps,touchesList,} from './liteXMLEditPlan';+import { findMalformedLiteXML } from './liteXMLWellFormed';import type {EditTitleArgs,EditTitleRuntimeResult,@@ -485,7 +486,9 @@ export class EditorRuntime {const before = readLiteXML();const document = indexLiteXMLDocument(before);- const problem = findLiteXMLEditStepProblem(operation, document);+ const problem =+ ('litexml' in operation && findMalformedLiteXML(operation.litexml)) ||+ findLiteXMLEditStepProblem(operation, document);if (problem)throw new Error(`${describeLiteXMLEditStep(step, operations.length)}: ${problem}`);diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.tsindex ca270071044..9a248aac77c 100644--- a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts@@ -207,6 +207,22 @@ describe('EditorRuntime - Real Cases', () => {expect(result.results[1]).toMatchObject({ action: 'insert', success: true });});+ it('explains a fragment with a raw "<" instead of reporting a rejection', async () => {+ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'insert',+ afterId: idOf('p', 'tail'),+ litexml: '<p>lh provider test -m <model> https://api.deepseek.com/v1</p>',+ },+ ],+ });++ expect(result.successCount).toBe(0);+ expect(result.results[0].error).toContain('<model> is never closed');+ expect(result.results[0].error).not.toContain('rejected it');+ });+it('keeps array order for inserts sharing a beforeId', async () => {const anchor = idOf('p', 'tail');const result = await runtime.modifyNodes({diff --git a/packages/editor-runtime/src/__tests__/liteXMLWellFormed.test.ts b/packages/editor-runtime/src/__tests__/liteXMLWellFormed.test.tsnew file mode 100644index 00000000000..5edb9527fe4--- /dev/null+++ b/packages/editor-runtime/src/__tests__/liteXMLWellFormed.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { findMalformedLiteXML } from '../liteXMLWellFormed';++describe('findMalformedLiteXML', () => {+ it('accepts well-formed fragments, including bare URLs and self-closing tags', () => {+ expect(+ findMalformedLiteXML('<p><span>see https://api.deepseek.com/v1</span></p>'),+ ).toBeUndefined();+ expect(findMalformedLiteXML('<p>a<br/>b</p><p>P&L <model></p>')).toBeUndefined();+ expect(findMalformedLiteXML(['<p id="ab">x</p>', '<li id="cd">y</li>'])).toBeUndefined();+ });++ it('names a raw tag-like word in the text that is never closed', () => {+ expect(findMalformedLiteXML('<ol><li>run lh provider test -m <model> now</li></ol>')).toContain(+ '<model> is never closed',+ );+ expect(findMalformedLiteXML('<p>a List<string> field</p>')).toContain(+ '<string> is never closed',+ );+ });++ it('reports a tag that is opened but never finished with ">"', () => {+ expect(findMalformedLiteXML('<p>a <b c</p>')).toContain(+ '"<b c" starts a tag that is never closed',+ );+ });++ it('accepts a raw "<" or "&" the parser reads as text', () => {+ for (const text of ['1 <2 and 3', 'if a < b then', 'x << y', 'A & B < C']) {+ expect(findMalformedLiteXML(`<p>${text}</p>`)).toBeUndefined();+ }+ });++ it('reports a closing tag without an opening tag', () => {+ expect(findMalformedLiteXML('<p>x</span></p>')).toContain(+ '</span> has no matching opening tag',+ );+ });++ it('tells the caller how to write the text instead', () => {+ expect(findMalformedLiteXML('<p>-m <model></p>')).toContain('"<"');+ });++ it('checks every fragment of a multi-fragment modify', () => {+ expect(findMalformedLiteXML(['<p id="ab">ok</p>', '<p id="cd">a < b c</p>'])).toBeUndefined();+ expect(findMalformedLiteXML(['<p id="ab">ok</p>', '<p id="cd">-m <model></p>'])).toContain(+ '<model>',+ );+ });+});diff --git a/packages/editor-runtime/src/index.ts b/packages/editor-runtime/src/index.tsindex 907542e5a15..8e34a7dce81 100644--- a/packages/editor-runtime/src/index.ts+++ b/packages/editor-runtime/src/index.ts@@ -1,4 +1,5 @@export { EditorRuntime, type LiteXMLBatchOperation } from './EditorRuntime';export { formatModifyNodesResult } from './formatModifyNodesResult';export * from './liteXMLEditPlan';+export * from './liteXMLWellFormed';export * from './types';diff --git a/packages/editor-runtime/src/liteXMLWellFormed.ts b/packages/editor-runtime/src/liteXMLWellFormed.tsnew file mode 100644index 00000000000..08aed1d0697--- /dev/null+++ b/packages/editor-runtime/src/liteXMLWellFormed.ts@@ -0,0 +1,51 @@+const MARKUP_TAG_PATTERN = /<(\/?)([a-z][\w.:-]*)(?:\s[^<>]*|\/)?>/gi;++// `<` followed by a letter or `/` opens a tag for the XML parser; a raw `<`+// before a digit, space or another `<` is accepted as text.+const TAG_START_PATTERN = /<\/?[a-z]/gi;+const COMPLETE_TAG_PATTERN = /<\/?[a-z][\w.:-]*(?:\s[^<>]*|\/)?>/iy;++const describeMalformedMarkup = (litexml: string): string | undefined => {+ for (const { index } of litexml.matchAll(TAG_START_PATTERN)) {+ COMPLETE_TAG_PATTERN.lastIndex = index;+ if (!COMPLETE_TAG_PATTERN.test(litexml)) {+ const fragment = litexml+ .slice(index)+ .match(/^<[^<]{0,24}/)![0]+ .trimEnd();+ return `"${fragment}" starts a tag that is never closed with ">"`;+ }+ }++ const open: string[] = [];++ for (const [tag, closing, name] of litexml.matchAll(MARKUP_TAG_PATTERN)) {+ if (tag.endsWith('/>')) continue;+ if (!closing) {+ open.push(name);+ continue;+ }++ const at = open.lastIndexOf(name);+ if (at === -1) return `</${name}> has no matching opening tag`;+ if (at !== open.length - 1) return `<${open.at(-1)}> is never closed`;+ open.pop();+ }++ return open.length > 0 ? `<${open.at(-1)}> is never closed` : undefined;+};++/**+ * The editor parses LiteXML as XML and silently drops an operation whose+ * fragment is not well-formed β most often text that contains a raw `<`, such+ * as `-m <model>` or `List<string>`. Explain that instead of reporting a+ * rejection the caller cannot act on.+ */+export const findMalformedLiteXML = (litexml: string | string[]): string | undefined => {+ for (const fragment of Array.isArray(litexml) ? litexml : [litexml]) {+ const problem = describeMalformedMarkup(fragment);+ if (problem) {+ return `litexml is not well-formed XML (${problem}). Text cannot contain a raw "<": write a literal "<" as "<" and "&" as "&" (e.g. "<model>")`;+ }+ }+};