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(page-agent): pair id-less rewrites into modifications and keep scroll on accept all (#22141)

Innei9b15ab34402f
diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
index c6cf744de18..3bf3b283f06 100644
--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
+++ b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts
@@ -127,6 +127,33 @@ describe('diffLiteXMLBlocks against a real editor', () => {
},
);
+ it.each([DiffAction.Accept, DiffAction.Reject])(
+ 'reviews a paragraph rewritten without its id as one modification, action %s',
+ async (action) => {
+ const page = await setup(
+ 'intro\n\n所以这块我们到现在也还没想清楚。至少我觉得,资源的使用权限得分开看。\n\ntail',
+ );
+ const before = page.markdownOf();
+ const rewritten =
+ 'intro\n\n所以这块我们到现在也还没想清楚。表面上是在分资源的使用权限。\n\n我隐约觉得,这碰到了最根本的关系。\n\ntail';
+ const { result } = await page.apply((xml) =>
+ xml.replace(
+ /<p id="[^"]+">(?:(?!<\/p>)[\s\S])*至少我觉得[\s\S]*?<\/p>/,
+ '<p>所以这块我们到现在也还没想清楚。表面上是在分资源的使用权限。</p><p>我隐约觉得,这碰到了最根本的关系。</p>',
+ ),
+ );
+
+ expect(result.successCount).toBe(result.totalCount);
+ const json = JSON.stringify(page.json());
+ expect(json).toContain('"diffType":"modify"');
+ expect(json).not.toContain('"diffType":"remove"');
+ expect(page.markdownOf()).toBe(rewritten);
+ await page.resolve(action);
+ expect(JSON.stringify(page.json())).not.toContain('"type":"diff"');
+ expect(page.markdownOf()).toBe(action === DiffAction.Accept ? rewritten : before);
+ },
+ );
+
it.each([DiffAction.Accept, DiffAction.Reject])(
'preserves nested list structure when resolving action %s',
async (action) => {
diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
index e939b8adba8..ce4df7c3dc7 100644
--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
+++ b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts
@@ -77,14 +77,86 @@ describe('diffLiteXMLBlocks', () => {
});
it('orders operations insert, then modify, then remove, all on original ids', () => {
- const result = ok(doc(A, B, C), doc('<p id="a">A2</p>', '<p>new</p>', C));
+ const result = ok(doc(A, B, C), doc('<p id="a">A2</p>', '<h2>new</h2>', C));
expect(result.operations.map((operation) => operation.action)).toEqual([
'insert',
'modify',
'remove',
]);
- expect(result.operations[0]).toEqual({ action: 'insert', afterId: 'a', litexml: '<p>new</p>' });
+ expect(result.operations[0]).toEqual({
+ action: 'insert',
+ afterId: 'a',
+ litexml: '<h2>new</h2>',
+ });
+ });
+
+ it('modifies a block rewritten in place without its id', () => {
+ const result = ok(doc(A, '<p id="b">B</p>', C), doc(A, '<p>B rewritten</p>', C));
+
+ expect(result.operations).toEqual([{ action: 'modify', litexml: '<p id="b">B rewritten</p>' }]);
+ expect(result.summary).toEqual({ inserted: 0, modified: 1, removed: 0 });
+ });
+
+ it('pairs a rewrite without its id with the most similar original in the same gap', () => {
+ const original = doc(
+ A,
+ '<p id="b">所以这块我们到现在也还没想清楚。至少我觉得,资源的使用权限、执行的成本和产物的归属,得分开看。</p>',
+ C,
+ );
+ const edited = doc(
+ A,
+ '<p>所以这块我们到现在也还没想清楚。表面上是在分资源的使用权限、执行成本和产物归属。</p>',
+ '<p>我隐约觉得,这可能碰到了人和 agent 一起工作时最根本的关系。</p>',
+ C,
+ );
+
+ const result = ok(original, edited);
+
+ expect(result.operations).toEqual([
+ {
+ action: 'insert',
+ afterId: 'b',
+ litexml: '<p>我隐约觉得,这可能碰到了人和 agent 一起工作时最根本的关系。</p>',
+ },
+ {
+ action: 'modify',
+ litexml:
+ '<p id="b">所以这块我们到现在也还没想清楚。表面上是在分资源的使用权限、执行成本和产物归属。</p>',
+ },
+ ]);
+ expect(result.summary).toEqual({ inserted: 1, modified: 1, removed: 0 });
+ });
+
+ it('drops a rewrite without ids that reads the same as the original', () => {
+ const result = ok(
+ doc(A, '<p id="b"><span id="s">Same text</span></p>', C),
+ doc(A, '<p><span>Same text</span></p>', C),
+ );
+
+ expect(result.operations).toEqual([]);
+ });
+
+ it('keeps unrelated replacements as insert plus remove', () => {
+ const result = ok(
+ doc(A, '<p id="b">Meeting notes for Monday</p>', '<p id="d">Agenda</p>', C),
+ doc(A, '<p>Budget table for Q3 planning</p>', C),
+ );
+
+ expect(result.operations.map((operation) => operation.action)).toEqual([
+ 'insert',
+ 'remove',
+ 'remove',
+ ]);
+ });
+
+ it('does not pair blocks of different tags', () => {
+ const result = ok(doc(A, '<p id="b">Title</p>', C), doc(A, '<h2>Title</h2>', C));
+
+ expect(result.operations).toEqual([
+ { action: 'insert', afterId: 'a', litexml: '<h2>Title</h2>' },
+ { action: 'remove', id: 'b' },
+ ]);
});
it('turns a moved block into remove plus an id-free insert', () => {
diff --git a/packages/editor-runtime/src/liteXMLBlockDiff.ts b/packages/editor-runtime/src/liteXMLBlockDiff.ts
index 17aa2cb16af..787bc2ec43d 100644
--- a/packages/editor-runtime/src/liteXMLBlockDiff.ts
+++ b/packages/editor-runtime/src/liteXMLBlockDiff.ts
@@ -244,6 +244,77 @@ const longestCommonSubsequence = (a: string[], b: string[]): Set<string> => {
return common;
};
+const REWRITE_SIMILARITY = 0.3;
+
+const withId = (payload: string, id: string) =>
+ payload.replace(/^<([a-z][\w-]*)/i, `<$1 id="${id}"`);
+
+const bigrams = (text: string) => {
+ const compact = text.replaceAll(/\s+/g, '');
+ const counts = new Map<string, number>();
+ for (let i = 0; i < compact.length - 1; i += 1) {
+ const gram = compact.slice(i, i + 2);
+ counts.set(gram, (counts.get(gram) ?? 0) + 1);
+ }
+ return counts;
+};
+
+const textSimilarity = (a: string, b: string) => {
+ const gramsA = bigrams(a);
+ const gramsB = bigrams(b);
+ let shared = 0;
+ let total = 0;
+ for (const [gram, count] of gramsA) {
+ shared += Math.min(count, gramsB.get(gram) ?? 0);
+ total += count;
+ }
+ for (const count of gramsB.values()) total += count;
+ if (total === 0) return a === b ? 1 : 0;
+ return (2 * shared) / total;
+};
+
+// Shell edits of /doc.xml often rewrite a block without its id. Reviewing that as a
+// remove plus an insert splits the old and new text apart, so a new block that sits
+// where an original disappeared, with the same tag and similar text, modifies it.
+const pairRewrites = (removed: ParsedBlock[], inserted: ParsedBlock[]): [number, number][] => {
+ const single = removed.length === 1 && inserted.length === 1;
+ const score = (i: number, j: number) => {
+ if (removed[i].tag !== inserted[j].tag) return -1;
+ if (single) return 1;
+ const similarity = textSimilarity(removed[i].text, inserted[j].text);
+ return similarity >= REWRITE_SIMILARITY ? similarity : -1;
+ };
+
+ const best = Array.from(
+ { length: removed.length + 1 },
+ () => new Float64Array(inserted.length + 1),
+ );
+ for (let i = removed.length - 1; i >= 0; i -= 1) {
+ for (let j = inserted.length - 1; j >= 0; j -= 1) {
+ const pair = score(i, j);
+ best[i][j] = Math.max(
+ best[i + 1][j],
+ best[i][j + 1],
+ pair >= 0 ? pair + best[i + 1][j + 1] : 0,
+ );
+ }
+ }
+
+ const pairs: [number, number][] = [];
+ let i = 0;
+ let j = 0;
+ while (i < removed.length && j < inserted.length) {
+ const pair = score(i, j);
+ if (pair >= 0 && best[i][j] === pair + best[i + 1][j + 1]) {
+ pairs.push([i, j]);
+ i += 1;
+ j += 1;
+ } else if (best[i][j] === best[i + 1][j]) i += 1;
+ else j += 1;
+ }
+ return pairs;
+};
+
export const diffLiteXMLBlocks = (original: string, edited: string): LiteXMLBlockDiffResult => {
const before = parseBlocks(original);
if (typeof before === 'string') return { ok: false, reason: `original document: ${before}` };
@@ -279,6 +350,30 @@ export const diffLiteXMLBlocks = (original: string, edited: string): LiteXMLBloc
candidates.filter((id): id is string => !!id),
);
+ const removedGaps: ParsedBlock[][] = [[]];
+ for (const block of before) {
+ if (!block.id) continue;
+ if (kept.has(block.id)) removedGaps.push([]);
+ else removedGaps.at(-1)!.push(block);
+ }
+ const insertedGaps: number[][] = [[]];
+ after.forEach((block, index) => {
+ const id = candidates[index];
+ if (id && kept.has(id)) insertedGaps.push([]);
+ else insertedGaps.at(-1)!.push(index);
+ });
+
+ const rewrites = new Map<number, string>();
+ removedGaps.forEach((removedBlocks, gap) => {
+ const insertedIndexes = insertedGaps[gap] ?? [];
+ const pairs = pairRewrites(
+ removedBlocks,
+ insertedIndexes.map((index) => after[index]),
+ );
+ for (const [i, j] of pairs) rewrites.set(insertedIndexes[j], removedBlocks[i].id!);
+ });
+ const rewritten = new Set(rewrites.values());
+
const inserts: ModifyOperation[] = [];
const modifies: ModifyOperation[] = [];
let pending: string[] = [];
@@ -294,21 +389,31 @@ export const diffLiteXMLBlocks = (original: string, edited: string): LiteXMLBloc
};
after.forEach((block, index) => {
- const id = candidates[index];
- if (!id || !kept.has(id)) {
+ const candidate = candidates[index];
+ const rewriteOf = rewrites.get(index);
+ const id = candidate && kept.has(candidate) ? candidate : rewriteOf;
+ if (!id) {
pending.push(toPayload(block.tokens, { stripIds: true }));
return;
}
flush(lastKeptId ? { afterId: lastKeptId } : { beforeId: id });
lastKeptId = id;
- if (block.xml !== originalById.get(id)!.xml) {
+ const previous = originalById.get(id)!;
+ if (rewriteOf) {
+ if (block.bare !== previous.bare) {
+ modifies.push({
+ action: 'modify',
+ litexml: withId(toPayload(block.tokens, { stripIds: true }), id),
+ });
+ }
+ } else if (block.xml !== previous.xml) {
modifies.push({ action: 'modify', litexml: toPayload(block.tokens) });
}
});
flush({ afterId: lastKeptId ?? originalIds.at(-1)! });
const removes: ModifyOperation[] = originalIds
- .filter((id) => !kept.has(id))
+ .filter((id) => !kept.has(id) && !rewritten.has(id))
.map((id) => ({ action: 'remove', id }));
return {
diff --git a/src/features/EditorCanvas/DiffAllToolbar.tsx b/src/features/EditorCanvas/DiffAllToolbar.tsx
index 096181f7967..ac508898d2a 100644
--- a/src/features/EditorCanvas/DiffAllToolbar.tsx
+++ b/src/features/EditorCanvas/DiffAllToolbar.tsx
@@ -1,7 +1,7 @@
'use client';
import type { IEditor } from '@lobehub/editor';
-import { DiffAction, LITEXML_DIFFNODE_ALL_COMMAND } from '@lobehub/editor';
+import { DiffAction } from '@lobehub/editor';
import { Block, Button, createStaticStyles, cssVar, cx, Flexbox, Icon } from '@lobehub/ui';
import { Check, X } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
@@ -10,6 +10,8 @@ import { useTranslation } from 'react-i18next';
import { useIsDark } from '@/hooks/useIsDark';
import { useDocumentStore } from '@/store/document';
+import { resolveAllDiffs } from './resolveAllDiffs';
+
const styles = createStaticStyles(({ css }) => ({
container: css`
position: absolute;
@@ -135,9 +137,7 @@ const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId, editor }) => {
size={'small'}
type="text"
onClick={async () => {
- editor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
- action: DiffAction.Reject,
- });
+ resolveAllDiffs(editor, DiffAction.Reject);
await handleSave();
}}
>
@@ -148,9 +148,7 @@ const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId, editor }) => {
size={'small'}
type="fill"
onClick={async () => {
- editor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
- action: DiffAction.Accept,
- });
+ resolveAllDiffs(editor, DiffAction.Accept);
await handleSave();
}}
>
diff --git a/src/features/EditorCanvas/resolveAllDiffs.test.ts b/src/features/EditorCanvas/resolveAllDiffs.test.ts
new file mode 100644
index 00000000000..bcc87504fcb
--- /dev/null
+++ b/src/features/EditorCanvas/resolveAllDiffs.test.ts
@@ -0,0 +1,68 @@
+import { EditorRuntime } from '@lobechat/editor-runtime';
+import type { IEditor } from '@lobehub/editor';
+import {
+ CommonPlugin,
+ DiffAction,
+ Kernel,
+ LitexmlPlugin,
+ MarkdownPlugin,
+ moment,
+} from '@lobehub/editor';
+import { $getSelection } from 'lexical';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { resolveAllDiffs } from './resolveAllDiffs';
+
+const mountPageWithPendingInsert = async () => {
+ const root = document.createElement('div');
+ root.contentEditable = 'true';
+ document.body.append(root);
+
+ const editor = new Kernel() as unknown as IEditor;
+ editor.registerPlugins([CommonPlugin, MarkdownPlugin, LitexmlPlugin]);
+ editor.setRootElement(root);
+ editor.setDocument('markdown', 'first\n\nsecond\n\nthird');
+ await moment();
+
+ const runtime = new EditorRuntime();
+ runtime.setEditor(editor);
+ runtime.setTitleHandlers(
+ () => {},
+ () => 'Title',
+ );
+ const xml = editor.getDocument('litexml') as unknown as string;
+ const firstId = xml.match(/<p id="([^"]+)"/)![1];
+ await runtime.modifyNodes({
+ operations: [{ action: 'insert', afterId: firstId, litexml: '<p>added</p>' }],
+ });
+ await moment();
+
+ return { editor, root };
+};
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+describe('resolveAllDiffs', () => {
+ it.each([DiffAction.Accept, DiffAction.Reject])(
+ 'leaves the caret off the document end after action %s',
+ async (action) => {
+ const { editor, root } = await mountPageWithPendingInsert();
+ expect(root.querySelector('[data-diff-type]')).not.toBeNull();
+
+ resolveAllDiffs(editor, action);
+ await moment();
+
+ expect(root.querySelector('[data-diff-type]')).toBeNull();
+ const selection = editor
+ .getLexicalEditor()!
+ .getEditorState()
+ .read(() => $getSelection());
+ expect(selection).toBeNull();
+ const domSelection = window.getSelection();
+ const anchor = domSelection?.rangeCount ? domSelection.anchorNode : null;
+ expect(anchor && root.lastElementChild?.contains(anchor)).toBeFalsy();
+ },
+ );
+});
diff --git a/src/features/EditorCanvas/resolveAllDiffs.ts b/src/features/EditorCanvas/resolveAllDiffs.ts
new file mode 100644
index 00000000000..94b1b1f6544
--- /dev/null
+++ b/src/features/EditorCanvas/resolveAllDiffs.ts
@@ -0,0 +1,16 @@
+import type { DiffAction, IEditor } from '@lobehub/editor';
+import { LITEXML_DIFFNODE_ALL_COMMAND } from '@lobehub/editor';
+import { $setSelection } from 'lexical';
+
+export const resolveAllDiffs = (editor: IEditor, action: DiffAction) => {
+ const lexicalEditor = editor.getLexicalEditor();
+ if (!lexicalEditor) return;
+
+ // Resolving a top-level diff selects the end of its parent, the root, which scrolls
+ // the page to the bottom. The command queues its update as a nested one, so the
+ // selection reset is queued too: both land in this commit, the reset last.
+ lexicalEditor.update(() => {
+ lexicalEditor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, { action });
+ lexicalEditor.update(() => $setSelection(null));
+ });
+};