Skip to content

Build your personal knowledge base with Trilium Notes

feat(ai-assistant): answer a run that changed nothing instead of diffing it

Elian Doran264f1eccc2fa
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 7b55d89c45..79e8484e3c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3930,6 +3930,7 @@
"link-embed-widget": "link embed widget",
"link-mention-widget": "link mention widget",
"link-preview": "Link preview",
+ "looks-good-already-nothing-to-change": "Looks good already, nothing to change.",
"markdown-import": "Markdown import",
"markdown-import-from-clipboard": "Markdown import from clipboard",
"math-editor-unavailable": "Math editor unavailable",
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 851758ab54..d620e34c30 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
@@ -109,4 +109,20 @@ describe("diffAiResponse", () => {
it("treats a response with nothing to align against as entirely rewritten", () => {
expect(diffAiResponse("", "<p>generated</p>").rewriteRatio).toBe(1);
});
+
+ // Proofreading text that has nothing wrong with it. The container the response adds is not a
+ // change — otherwise an untouched response could never be reported as untouched.
+ it("reports a response that changed nothing, container differences aside", () => {
+ expect(diffAiResponse(ORIGINAL, ORIGINAL).isUnchanged).toBe(true);
+ expect(diffAiResponse("It is already perfect.", "<p>It is already perfect.</p>").isUnchanged).toBe(true);
+
+ for (const [name, changed] of [
+ ["a word", ORIGINAL.replace("every day", "daily")],
+ ["a block", `${ORIGINAL}<p>One more thought.</p>`],
+ // The same words, but the note would come out different — so not "no changes".
+ ["only the markup", ORIGINAL.replace("<h2>Backups</h2>", "<h3>Backups</h3>")]
+ ] as const) {
+ expect(diffAiResponse(ORIGINAL, changed).isUnchanged, name).toBe(false);
+ }
+ });
});
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 9cb10d0b5c..9f34b6e740 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_diff.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.ts
@@ -82,10 +82,33 @@ export default function diffAiResponse(oldHtml: string, newHtml: string): AiDiff
const responseLength = newBlocks.reduce((total, block) => total + block.text.length, 0);
return {
html: chunks.join(""),
- rewriteRatio: responseLength ? rewrittenLength / responseLength : 0
+ rewriteRatio: responseLength ? rewrittenLength / responseLength : 0,
+ isUnchanged: isSameContent(oldBlocks, newBlocks)
};
}
+/**
+ * Whether the response came back as the content it was given — what proofreading text that has
+ * nothing wrong with it produces.
+ *
+ * Blocks with a container on both sides are compared as markup, so the same words moved into a
+ * different heading, or a paragraph rewrapped in a callout, still counts as a change: the note
+ * would come out different. Where one side has no container the comparison drops to what the two
+ * hold, because a selection made inside a block is captured without it (see {@link kindOf}) and
+ * treating that as a change would mean never reporting an untouched response as untouched.
+ */
+function isSameContent(before: Block[], after: Block[]): boolean {
+ return before.length === after.length && before.every((block, index) => {
+ const counterpart = after[index];
+ if (!counterpart) {
+ return false;
+ }
+ return block.element && counterpart.element
+ ? block.html === counterpart.html
+ : block.inner === counterpart.inner;
+ });
+}
+
/**
* How much of two blocks' words must coincide before their difference is worth marking word by
* word. Below it the word differ has nothing to align on and produces noise, so the pair is shown
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index 1e51503cc4..ebc958cd4a 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -65,6 +65,15 @@ export interface AiDiffResult {
* which is the behaviour of a plain word-level diff.
*/
rewriteRatio?: number;
+ /**
+ * Whether the response *is* the content it was given — what proofreading text with nothing
+ * wrong with it produces. The review says so outright rather than offering a diff with no
+ * marks in it, which reads as a diff that failed.
+ *
+ * Optional, and only a renderer that compares the two sides itself can answer it: an empty
+ * diff and an unchanged one are the same string.
+ */
+ isUnchanged?: boolean;
}
/**
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
index 21d463e96c..2c83e1f2da 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
@@ -86,6 +86,32 @@ describe("AiAssistantFormView", () => {
expect(form.tryAgainButtonView.isEnabled).toBe(true);
});
+ it("stands a message in for a response that changed nothing", () => {
+ const form = makeForm();
+ const empty = () => form.element?.querySelector(".ck-ai-assistant-form__empty");
+
+ expect(empty()?.classList.contains("ck-hidden")).toBe(true);
+
+ form.beginStreaming();
+ form.setPreview("<p>already perfect</p>");
+ form.enterReview({ hasContent: true, isUnchanged: true });
+
+ expect(form.isUnchanged).toBe(true);
+ expect(empty()?.classList.contains("ck-hidden")).toBe(false);
+ expect(empty()?.textContent).toContain("nothing to change");
+ // The response is the text the user is already looking at, so it takes the place of the
+ // preview rather than being shown above the message saying it changed nothing.
+ expect(form.previewView.isVisible).toBe(false);
+ // Nothing changed, so there is no second view of it to offer either.
+ expect(form.hasDiff).toBe(false);
+ expect(form.viewMode).toBe("result");
+
+ // The next run starts over rather than carrying the message into it.
+ form.beginStreaming();
+ expect(empty()?.classList.contains("ck-hidden")).toBe(true);
+ expect(form.previewView.isVisible).toBe(true);
+ });
+
it("opens the review on the view the caller names, keeping the other one click away", () => {
const form = makeForm();
form.beginStreaming();
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
index f85d7f5fa8..c1e0747aed 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -1,8 +1,9 @@
-import { IconArrowUp, IconRefresh, IconStop } from "@ckeditor/ckeditor5-icons";
+import { IconArrowUp, IconCheck, IconRefresh, IconStop } from "@ckeditor/ckeditor5-icons";
import {
ButtonView,
FocusCycler,
FocusTracker,
+ IconView,
InputTextView,
KeystrokeHandler,
submitHandler,
@@ -33,6 +34,8 @@ export interface AiReviewOptions {
usageText?: string;
/** Which view to open on. Defaults to "changes" whenever there is a diff to show. */
viewMode?: AiReviewView;
+ /** Whether the response came back as the content it was given, which the review says outright. */
+ isUnchanged?: boolean;
}
/**
@@ -53,6 +56,8 @@ export default class AiAssistantFormView extends View {
declare public viewMode: AiReviewView;
/** Whether the current review has a diff to offer; controls the view-mode toggle. */
declare public hasDiff: boolean;
+ /** Whether the review is of a response that changed nothing; shows the notice saying so. */
+ declare public isUnchanged: boolean;
/** The run's cost line ("model · tokens · price"), shown in the review actions row. */
declare public usageText: string;
@@ -87,6 +92,7 @@ export default class AiAssistantFormView extends View {
this.set("errorMessage", "");
this.set("viewMode", "result");
this.set("hasDiff", false);
+ this.set("isUnchanged", false);
this.set("usageText", "");
// Re-render the preview from the stored contents whenever the toggle flips.
@@ -97,7 +103,13 @@ export default class AiAssistantFormView extends View {
this.promptInputView = this._createPromptInput(locale);
this.sendButtonView = this._createSendButton(locale);
this.previewView = new AiPreviewView(locale);
- this.previewView.bind("isVisible").to(this, "phase", (phase) => phase !== "prompt");
+ // A response that changed nothing is the text the user is already looking at, so the
+ // placeholder stands in its place rather than sitting under a copy of it.
+ this.previewView.bind("isVisible").to(
+ this, "phase",
+ this, "isUnchanged",
+ (phase, isUnchanged) => phase !== "prompt" && !isUnchanged
+ );
// Takes Send's place in the prompt row while a run is in flight: the control that acts on
// the run belongs where the eye already is, and one icon replacing another keeps the row
@@ -186,6 +198,23 @@ export default class AiAssistantFormView extends View {
},
children: [{ text: bind.to("errorMessage") }]
},
+ {
+ // What the preview would have shown is the text the run was given, word for
+ // word, and a "Changes" view of it would be a diff with no marks in it — which
+ // reads as a diff that failed. So the answer is given as an answer.
+ tag: "div",
+ attributes: {
+ class: [
+ "ck",
+ "ck-ai-assistant-form__empty",
+ bind.if("isUnchanged", "ck-hidden", (isUnchanged) => !isUnchanged)
+ ]
+ },
+ children: [
+ createIcon(IconCheck),
+ { text: t("Looks good already — nothing to change.") }
+ ]
+ },
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },
@@ -262,6 +291,7 @@ export default class AiAssistantFormView extends View {
this._resultHtml = "";
this._diffHtml = "";
this.hasDiff = false;
+ this.isUnchanged = false;
this.viewMode = "result";
this.usageText = "";
this._renderPreview();
@@ -274,6 +304,7 @@ export default class AiAssistantFormView extends View {
this._resultHtml = "";
this._diffHtml = "";
this.hasDiff = false;
+ this.isUnchanged = false;
this.viewMode = "result";
this.usageText = "";
this._renderPreview();
@@ -290,8 +321,11 @@ export default class AiAssistantFormView extends View {
* for (the "Changes" view by default, whenever there is a diff), while a run that produced
* nothing falls back to the prompt phase, showing `errorMessage` when the run failed.
*/
- public enterReview({ hasContent, diffHtml, errorMessage = "", usageText = "", viewMode }: AiReviewOptions): void {
+ public enterReview({
+ hasContent, diffHtml, errorMessage = "", usageText = "", viewMode, isUnchanged = false
+ }: AiReviewOptions): void {
this.phase = hasContent ? "review" : "prompt";
+ this.isUnchanged = hasContent && isUnchanged;
this.errorMessage = errorMessage;
this._diffHtml = diffHtml ?? "";
this.hasDiff = hasContent && !!this._diffHtml;
@@ -383,6 +417,13 @@ export default class AiAssistantFormView extends View {
}
}
+/** A standalone glyph for a template. `IconView` takes its SVG through a property, not a call. */
+function createIcon(content: string): IconView {
+ const icon = new IconView();
+ icon.content = content;
+ return icon;
+}
+
/**
* The streaming preview: a plain non-editable `div` carrying the `ck-content` class so the
* response renders with the same styles it will have once inserted into the note.
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
index 6d03de7c56..d98ba91446 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
@@ -142,6 +142,7 @@ function openForm(editor: ClassicEditor) {
phase: string;
viewMode: string;
hasDiff: boolean;
+ isUnchanged: boolean;
fire(event: string): void;
};
}
@@ -401,6 +402,15 @@ describe("AiAssistantUI toolbar entry", () => {
expect((await review(diff, "translate")).viewMode).toBe("result");
});
+ it("withholds the diff of a response the differ reports as unchanged", async () => {
+ const form = await review(() => ({ html: "<p>done</p>", isUnchanged: true }), "fixTypos");
+
+ // The form says so in words; a diff with no marks in it reads as a diff that failed.
+ expect(form.isUnchanged).toBe(true);
+ expect(form.hasDiff).toBe(false);
+ expect(form.viewMode).toBe("result");
+ });
+
it("is the result when the diff reports the response as mostly a rewrite", async () => {
// The same call the differ makes for a response it could not align with its source.
const form = await review(() => ({ html: "<ins>done</ins>", rewriteRatio: 1 }), "fixTypos");
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index 4ed4c56917..ec1f9a6b2a 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -438,7 +438,10 @@ export default class AiAssistantUI extends Plugin {
const diff = this._buildDiff();
form.enterReview({
hasContent: !!this._cumulative,
- diffHtml: diff?.html,
+ // A response that changed nothing has a diff with no marks in it, which reads as a
+ // diff that failed. The review says so in words instead, and offers no view of it.
+ diffHtml: diff?.isUnchanged ? null : diff?.html,
+ isUnchanged: diff?.isUnchanged,
errorMessage,
usageText: this._formatUsage(usage),
viewMode: this._resolveReviewView(diff)
@@ -510,8 +513,8 @@ export default class AiAssistantUI extends Plugin {
try {
// A renderer may answer with the diff alone or with the diff and what it made of it.
const result = diff(this._previousContext, this._cumulative);
- const { html, rewriteRatio }: AiDiffResult = typeof result === "string" ? { html: result } : result;
- return { html: this._sanitize(html), rewriteRatio };
+ const normalized: AiDiffResult = typeof result === "string" ? { html: result } : result;
+ return { ...normalized, html: this._sanitize(normalized.html) };
} catch (error) {
// A host diff failure only costs the Changes view, never the response itself.
console.warn("AI assistant: diff renderer failed", error);
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
index 5a4f3fdda6..035ba3f0f0 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -101,6 +101,26 @@
color: var(--ck-color-base-error);
}
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--ck-spacing-medium);
+ min-height: 6em;
+ border: 1px solid var(--ck-color-base-border);
+ border-radius: var(--ck-border-radius);
+ padding: var(--ck-spacing-large);
+ background: var(--ck-color-base-background);
+ text-align: center;
+ opacity: 0.75;
+
+ & .ck-icon {
+ width: 2em;
+ height: 2em;
+ }
+}
+
.ck.ck-ai-assistant-form .ck-ai-assistant-form__actions {
display: flex;
justify-content: flex-end;