Skip to content

Build your personal knowledge base with Trilium Notes

fix(ai-assistant): judge the word diff on what it marked, not on what it was predicted to mark

Elian Doran8cfff97e591a
diff --git a/apps/client/src/widgets/type_widgets/text/ai_diff.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_diff.spec.ts
index d620e34c30..a7978f8684 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_diff.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.spec.ts
@@ -53,6 +53,36 @@ describe("diffAiResponse", () => {
);
});
+ // The prefilter reads two casings of one sentence as the same sentence — it compares lowercased
+ // words — while the word differ recognises not one of them, so this is the pair that gets past
+ // the block pass and comes back with every word of the paragraph marked twice.
+ it("shows a recased paragraph as a replacement rather than marking every word of it", () => {
+ const { html, rewriteRatio } = diffAiResponse(
+ "<p>Age, imaginemur numeros esse quasi scalas magicas quae deorsum descendunt!</p>",
+ "<p>AGE IMAGINEMVR NVMEROS ESSE QVASI SCALAS MAGICAS QVAE DEORSVM DESCENDVNT</p>"
+ );
+
+ expect(html).toBe([
+ "<del class=\"diffdel diffblock\"><p>Age, imaginemur numeros esse quasi scalas magicas quae deorsum descendunt!</p></del>",
+ "<ins class=\"diffins diffblock\"><p>AGE IMAGINEMVR NVMEROS ESSE QVASI SCALAS MAGICAS QVAE DEORSVM DESCENDVNT</p></ins>"
+ ].join(""));
+ expect(rewriteRatio).toBe(1);
+ });
+
+ // The other side of the same measurement: a text the model recased *in places* is still the
+ // text it was, and the marks land on the words that moved.
+ it("keeps the word diff when only some of a block came out marked", () => {
+ const { html } = diffAiResponse(
+ "<p>trilium keeps a copy of the database every day.</p>",
+ "<p>Trilium keeps a copy of the database every day.</p>"
+ );
+
+ expect(html).toBe(
+ "<p><del class=\"diffmod\">trilium</del><ins class=\"diffmod\">Trilium</ins>"
+ + " keeps a copy of the database every day.</p>"
+ );
+ });
+
it("marks an added paragraph as an addition, leaving the ratio to the rewrites", () => {
const expanded = ORIGINAL.replace("<p>You can", "<p>The copies live next to the database file.</p><p>You can");
const { html, rewriteRatio } = diffAiResponse(ORIGINAL, expanded);
diff --git a/apps/client/src/widgets/type_widgets/text/ai_diff.ts b/apps/client/src/widgets/type_widgets/text/ai_diff.ts
index 9f34b6e740..6beabb083b 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_diff.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.ts
@@ -18,7 +18,9 @@ import HtmlDiff from "htmldiff-js";
* against each other; only a pair that is still the same block — a container of the same kind, and
* enough words in common — is handed to the word differ, and only what the two containers hold is.
* A pair that is not is shown as what it is: the old block struck through, the response's block
- * after it. A block with no counterpart is a plain insertion or deletion.
+ * after it. A block with no counterpart is a plain insertion or deletion. The word differ is held
+ * to that same standard afterwards: a pair whose diff comes back marked end to end (see
+ * {@link markedRatio}) is shredded too, and is shown as the replacement it turned out to be.
*
* The second thing that falls out of the block pass is {@link AiDiffResult.rewriteRatio}: how much
* of the response the alignment gave up on. The review reads it to decide whether to open on the
@@ -48,8 +50,9 @@ export default function diffAiResponse(oldHtml: string, newHtml: string): AiDiff
const after = index < added.length ? added[index] : null;
if (before && after) {
- if (isSameBlockRewritten(before, after)) {
- chunks.push(diffInside(before, after));
+ const edited = isSameBlockRewritten(before, after) ? diffInside(before, after) : null;
+ if (edited) {
+ chunks.push(edited);
} else {
chunks.push(markBlock("del", before), markBlock("ins", after));
rewrittenLength += after.text.length;
@@ -116,6 +119,14 @@ function isSameContent(before: Block[], after: Block[]): boolean {
*/
const INLINE_DIFF_SIMILARITY = 0.4;
+/**
+ * How much of a pair's text a word-level diff may come out having marked before the pair is shown
+ * as a replacement instead. Past half of it the marks are no longer marks on a text — they are the
+ * old text and the new one interleaved a word at a time, which is the shape the block pass exists
+ * to avoid.
+ */
+const INLINE_DIFF_CHURN_LIMIT = 0.5;
+
/** A top-level piece of a fragment: what the block pass aligns, and the unit a mark is put on. */
interface Block {
/** The block's own HTML, as it will appear in the diff. */
@@ -233,7 +244,8 @@ function kindOf(block: Block): string {
}
/**
- * The word-level diff of a pair, put back inside the container the *response* gave it.
+ * The word-level diff of a pair, put back inside the container the *response* gave it, or null
+ * when the diff came out as noise and the pair is better shown as a replacement.
*
* Only what the blocks hold is diffed. The containers are rarely identical even when the block is
* the same one — the captured selection may have none at all, and a rewrapped paragraph carries
@@ -241,8 +253,35 @@ function kindOf(block: Block): string {
* tags that close in the wrong order, leaving the preview's parser to rebuild the result in
* whatever shape it likes.
*/
-function diffInside(before: Block, after: Block): string {
- return wrap(after, HtmlDiff.execute(before.inner, after.inner));
+function diffInside(before: Block, after: Block): string | null {
+ const diffed = HtmlDiff.execute(before.inner, after.inner);
+ return markedRatio(before, after, diffed) > INLINE_DIFF_CHURN_LIMIT ? null : wrap(after, diffed);
+}
+
+/**
+ * How much of a pair's text the word differ ended up marking, from 0 to 1.
+ *
+ * {@link similarity} only predicts this, and it predicts it over lowercased words with the
+ * punctuation dropped, because that is what makes it recognise a reworded sentence as the sentence
+ * it was. The word differ recognises none of that: change the case of a text and every word of it
+ * is a word it has never seen, so a pair the prefilter reads as near-identical comes back with a
+ * `<del>`/`<ins>` pair on each of its words — the whole text twice, alternating, which is unreadable
+ * in a way neither of the two texts is. Measuring the diff that was actually produced costs one
+ * parse and answers for every such case, so the prefilter is left to do what it is cheap at.
+ */
+function markedRatio(before: Block, after: Block, diffed: string): number {
+ const total = before.text.length + after.text.length;
+ if (!total) {
+ return 0;
+ }
+
+ const doc = new DOMParser().parseFromString(diffed, "text/html");
+ let marked = 0;
+ for (const mark of doc.body.querySelectorAll("ins, del")) {
+ marked += normalize(mark.textContent).length;
+ }
+
+ return marked / total;
}
/** Puts diffed content back inside a block's own container, attributes and all. */