Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): add a Result/Changes diff view to the AI assistant review

Elian Doran6ee1ea0ac909
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 615ef3a426..1def0c3f77 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2523,7 +2523,9 @@
"stop": "Stop",
"replace": "Replace",
"insert_below": "Insert below",
- "try_again": "Try again"
+ "try_again": "Try again",
+ "result": "Result",
+ "changes": "Changes"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 7afd0c7960..363f565504 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,6 +1,7 @@
import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, SnippetDefinition } from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
+import HtmlDiff from "htmldiff-js";
import { copyTextWithToast } from "../../../services/clipboard_ext.js";
import { t } from "../../../services/i18n.js";
@@ -183,7 +184,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
},
aiAssistant: {
// `undefined` when no LLM provider is configured, which disables the feature.
- stream: buildAiAssistantStream()
+ stream: buildAiAssistantStream(),
+ // The "Changes" review view: the same HTML-aware inline diff (`<ins>`/`<del>`
+ // markup) the revisions dialog uses.
+ diff: (oldHtml: string, newHtml: string) => HtmlDiff.execute(oldHtml, newHtml)
},
htmlSupport: {
allow: JSON.parse(options.get("allowedHtmlTags"))
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index ebcddb273b..90c3ce9181 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -14,7 +14,7 @@ export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";
-export type { AiAssistantConfig, AiCompletionRequest, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
+export type { AiAssistantConfig, AiCompletionRequest, AiDiffFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
export * from "./utils.js";
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 d5c09fd441..beabca93fd 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -34,10 +34,25 @@ export type AiStreamFunction = (
signal: AbortSignal
) => Promise<void>;
+/**
+ * Renders an inline HTML diff between two HTML fragments, returning HTML in which insertions and
+ * deletions are marked with `<ins>`/`<del>` elements (the `htmldiff-js` output convention, the
+ * same mechanism Trilium's revision dialog uses).
+ */
+export type AiDiffFunction = (oldHtml: string, newHtml: string) => string;
+
export interface AiAssistantConfig {
/**
* Streams a completion for a request. When absent (no LLM provider configured), the whole
* feature stays disabled.
*/
stream?: AiStreamFunction;
+
+ /**
+ * Renders the "Changes" view of the review phase: an inline diff of the response against the
+ * content it replaces. Optional — without it the review phase only shows the result. The diff
+ * is computed once per finished run, never against a partial stream (a half-streamed response
+ * would render as a sea of deletions).
+ */
+ diff?: AiDiffFunction;
}
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
new file mode 100644
index 0000000000..d17b077fed
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
@@ -0,0 +1,101 @@
+import { Locale } from "ckeditor5";
+import { afterEach, describe, expect, it } from "vitest";
+
+import AiAssistantFormView from "./ai_assistant_form.js";
+
+let form: AiAssistantFormView;
+
+function makeForm(): AiAssistantFormView {
+ form = new AiAssistantFormView(new Locale(), (_key, fallback) => fallback);
+ form.render();
+ return form;
+}
+
+function previewHtml(): string {
+ return form.previewView.element?.innerHTML ?? "";
+}
+
+afterEach(() => {
+ form?.destroy();
+});
+
+describe("AiAssistantFormView", () => {
+ it("starts in the prompt phase with the view-mode toggle hidden", () => {
+ const form = makeForm();
+ expect(form.phase).toBe("prompt");
+ expect(form.resultToggleView.isVisible).toBe(false);
+ expect(form.changesToggleView.isVisible).toBe(false);
+ });
+
+ it("streams into the preview and always shows the raw result while streaming", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ expect(form.phase).toBe("streaming");
+ expect(form.viewMode).toBe("result");
+
+ form.setPreview("<p>partial</p>");
+ expect(previewHtml()).toBe("<p>partial</p>");
+ });
+
+ it("defaults the review to the Changes view when a diff is available and toggles back", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ form.setPreview("<p>new</p>");
+ form.enterReview(true, "<p><del class=\"diffdel\">old</del><ins class=\"diffins\">new</ins></p>", "");
+
+ expect(form.phase).toBe("review");
+ expect(form.hasDiff).toBe(true);
+ expect(form.viewMode).toBe("changes");
+ expect(previewHtml()).toContain("diffins");
+ expect(form.resultToggleView.isVisible).toBe(true);
+ expect(form.changesToggleView.isOn).toBe(true);
+
+ form.resultToggleView.fire("execute");
+ expect(form.viewMode).toBe("result");
+ expect(previewHtml()).toBe("<p>new</p>");
+ expect(form.resultToggleView.isOn).toBe(true);
+
+ form.changesToggleView.fire("execute");
+ expect(previewHtml()).toContain("diffdel");
+ });
+
+ it("reviews without a diff in the Result view with the toggle hidden", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ form.setPreview("<p>generated</p>");
+ form.enterReview(true, null, "");
+
+ expect(form.phase).toBe("review");
+ expect(form.hasDiff).toBe(false);
+ expect(form.viewMode).toBe("result");
+ expect(previewHtml()).toBe("<p>generated</p>");
+ expect(form.changesToggleView.isVisible).toBe(false);
+ });
+
+ it("falls back to the prompt phase with the error when a run produced nothing", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ form.enterReview(false, null, "provider unreachable");
+
+ expect(form.phase).toBe("prompt");
+ expect(form.errorMessage).toBe("provider unreachable");
+ });
+
+ it("reset clears the stored contents and view-mode state", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ form.setPreview("<p>new</p>");
+ form.enterReview(true, "<p>diff</p>", "");
+
+ form.reset();
+ expect(form.phase).toBe("prompt");
+ expect(form.hasDiff).toBe(false);
+ expect(form.viewMode).toBe("result");
+ expect(previewHtml()).toBe("");
+
+ // A later streaming run must not resurrect the previous run's diff.
+ form.beginStreaming();
+ form.enterReview(true, null, "");
+ expect(previewHtml()).toBe("");
+ });
+});
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 0784657514..137827d23b 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -23,11 +23,15 @@ type Translate = (key: string, fallback: string) => string;
*/
export type AiAssistantFormPhase = "prompt" | "streaming" | "review";
+/** What the preview shows in the review phase: the response, or its diff against the context. */
+export type AiAssistantViewMode = "result" | "changes";
+
/**
* The AI assistant balloon: a prompt row, a read-only streaming preview styled like note content,
- * and the review actions. Purely presentational — the orchestration (markers, streaming, committing
- * to the model) lives in `AiAssistantUI`, which listens to this view's `submit`, `stop`, `replace`,
- * `insertBelow` and `tryAgain` events.
+ * and the review actions. In the review phase the preview can toggle between the plain result and
+ * an inline diff ("Changes"), when the host provides a diff renderer. Purely presentational — the
+ * orchestration (markers, streaming, diffing, committing to the model) lives in `AiAssistantUI`,
+ * which listens to this view's `submit`, `stop`, `replace`, `insertBelow` and `tryAgain` events.
*/
export default class AiAssistantFormView extends View {
@@ -36,9 +40,20 @@ export default class AiAssistantFormView extends View {
declare public query: string;
/** A transport/provider failure to surface; empty string when there is none. */
declare public errorMessage: string;
+ /** Which of the stored contents the preview shows. Only meaningful in the review phase. */
+ declare public viewMode: AiAssistantViewMode;
+ /** Whether the current review has a diff to offer; controls the view-mode toggle. */
+ declare public hasDiff: boolean;
+
+ /** The (sanitized) response HTML, kept for re-rendering when the view mode flips. */
+ private _resultHtml = "";
+ /** The (sanitized) diff HTML of the review phase, when the host provided one. */
+ private _diffHtml = "";
public readonly promptInputView: LabeledFieldView<InputTextView>;
public readonly sendButtonView: ButtonView;
+ public readonly resultToggleView: ButtonView;
+ public readonly changesToggleView: ButtonView;
public readonly previewView: AiPreviewView;
public readonly stopButtonView: ButtonView;
public readonly replaceButtonView: ButtonView;
@@ -57,7 +72,14 @@ export default class AiAssistantFormView extends View {
this.set("phase", "prompt");
this.set("query", "");
this.set("errorMessage", "");
+ this.set("viewMode", "result");
+ this.set("hasDiff", false);
+ // Re-render the preview from the stored contents whenever the toggle flips.
+ this.on("change:viewMode", () => this._renderPreview());
+
+ this.resultToggleView = this._createViewModeButton(locale, translate("ai_assistant.result", "Result"), "result");
+ this.changesToggleView = this._createViewModeButton(locale, translate("ai_assistant.changes", "Changes"), "changes");
this.promptInputView = this._createPromptInput(locale, translate);
this.sendButtonView = this._createSendButton(locale, translate);
this.previewView = new AiPreviewView(locale);
@@ -81,7 +103,15 @@ export default class AiAssistantFormView extends View {
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__heading"] },
- children: [{ text: translate("ai_assistant.title", "AI assistant") }]
+ children: [
+ {
+ tag: "span",
+ attributes: { class: ["ck", "ck-ai-assistant-form__title"] },
+ children: [{ text: translate("ai_assistant.title", "AI assistant") }]
+ },
+ this.resultToggleView,
+ this.changesToggleView
+ ]
},
this.previewView,
{
@@ -131,6 +161,8 @@ export default class AiAssistantFormView extends View {
submitHandler({ view: this });
const focusables = [
+ this.resultToggleView,
+ this.changesToggleView,
this.promptInputView,
this.sendButtonView,
this.stopButtonView,
@@ -163,34 +195,69 @@ export default class AiAssistantFormView extends View {
this.phase = "prompt";
this.query = "";
this.errorMessage = "";
- this.previewView.setContent("");
+ this._resultHtml = "";
+ this._diffHtml = "";
+ this.hasDiff = false;
+ this.viewMode = "result";
+ this._renderPreview();
}
- /** Enters the streaming phase with an empty preview. */
+ /** Enters the streaming phase with an empty preview. Streaming always shows the raw result. */
public beginStreaming(): void {
this.phase = "streaming";
this.errorMessage = "";
- this.previewView.setContent("");
+ this._resultHtml = "";
+ this._diffHtml = "";
+ this.hasDiff = false;
+ this.viewMode = "result";
+ this._renderPreview();
}
/** Renders the (sanitized, cumulative) response received so far. */
public setPreview(html: string): void {
- this.previewView.setContent(html);
+ this._resultHtml = html;
+ this._renderPreview();
}
/**
- * Leaves the streaming phase. With content the form enters review; a run that produced
- * nothing falls back to the prompt phase, showing `errorMessage` when the run failed.
+ * Leaves the streaming phase. With content the form enters review — defaulting to the
+ * "Changes" view when a diff is available — while a run that produced nothing falls back to
+ * the prompt phase, showing `errorMessage` when the run failed.
*/
- public endStreaming(hasContent: boolean, errorMessage: string): void {
+ public enterReview(hasContent: boolean, diffHtml: string | null, errorMessage: string): void {
this.phase = hasContent ? "review" : "prompt";
this.errorMessage = errorMessage;
+ this._diffHtml = diffHtml ?? "";
+ this.hasDiff = hasContent && !!this._diffHtml;
+ this.viewMode = this.hasDiff ? "changes" : "result";
+ this._renderPreview();
}
public focus(): void {
this._focusCycler.focusFirst();
}
+ /** Shows whichever stored content the current view mode selects. */
+ private _renderPreview(): void {
+ this.previewView.setContent(this.viewMode === "changes" && this._diffHtml ? this._diffHtml : this._resultHtml);
+ }
+
+ /** One half of the Result/Changes toggle, visible only when a review has a diff to offer. */
+ private _createViewModeButton(locale: Locale, label: string, mode: AiAssistantViewMode) {
+ const button = new ButtonView(locale);
+ button.set({ label, withText: true, isToggleable: true, class: "ck-ai-assistant-form__viewmode" });
+ button.bind("isOn").to(this, "viewMode", (viewMode) => viewMode === mode);
+ button.bind("isVisible").to(
+ this, "phase",
+ this, "hasDiff",
+ (phase, hasDiff) => phase === "review" && hasDiff
+ );
+ button.on("execute", () => {
+ this.viewMode = mode;
+ });
+ return button;
+ }
+
private _createPromptInput(locale: Locale, translate: Translate) {
const input = new LabeledFieldView(locale, createLabeledInputText);
input.label = translate("ai_assistant.prompt_label", "Ask AI to…");
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 574fb8d688..7c3a7a3277 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -138,6 +138,14 @@ export default class AiAssistantUI extends Plugin {
void this._run(this._lastQuery);
});
+ // The Result and Changes views usually differ in height; keep the balloon anchored.
+ this.listenTo(form, "change:viewMode", () => {
+ const balloon = this.editor.plugins.get(ContextualBalloon);
+ if (balloon.visibleView === form) {
+ balloon.updatePosition();
+ }
+ });
+
// Esc always dismisses. A click outside only dismisses an idle, empty form — mid-stream or
// with a response on screen it would silently throw the result away.
form.keystrokes.set("Esc", (_data, cancel) => {
@@ -229,7 +237,28 @@ export default class AiAssistantUI extends Plugin {
// Follow-up queries chain on the response ("now make it shorter"), premium-style.
this._context = this._cumulative;
}
- form.endStreaming(!!this._cumulative, errorMessage);
+ form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage);
+ }
+
+ /**
+ * The "Changes" view of the review: the finished response diffed against the context the run
+ * saw (`_previousContext` — so a follow-up query diffs against the response it refined, not
+ * the original selection). Only computed once the stream is complete; diffing a partial
+ * response would render everything not yet streamed as deleted. Null when the host provides
+ * no diff renderer or there is nothing to diff against (generate-from-scratch).
+ */
+ private _buildDiff(): string | null {
+ const diff = this.editor.config.get("aiAssistant")?.diff;
+ if (!diff || !this._cumulative || !this._previousContext) {
+ return null;
+ }
+ try {
+ return sanitizeAiHtml(diff(this._previousContext, this._cumulative));
+ } catch (error) {
+ // A host diff failure only costs the Changes view, never the response itself.
+ console.warn("AI assistant: diff renderer failed", error);
+ return null;
+ }
}
/**
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 a024eebffe..e938047a63 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -7,9 +7,20 @@
}
.ck.ck-ai-assistant-form .ck-ai-assistant-form__heading {
+ display: flex;
+ align-items: center;
+ gap: var(--ck-spacing-small);
font-weight: bold;
}
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__title {
+ flex-grow: 1;
+}
+
+.ck.ck-ai-assistant-form .ck-button.ck-ai-assistant-form__viewmode {
+ font-weight: normal;
+}
+
.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row {
display: flex;
align-items: flex-end;
@@ -48,6 +59,42 @@
display: none;
}
+/* The inline diff shown by the "Changes" view (htmldiff-js `ins`/`del` markup, the same
+ convention the revisions dialog styles). Colors are self-contained rather than borrowing the
+ client's Bootstrap variables, so the plugin package stays host-agnostic. */
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins {
+ text-decoration: none;
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins.diffins,
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins.diffmod {
+ background-color: rgba(63, 185, 80, 0.25);
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del {
+ text-decoration: line-through;
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del.diffdel,
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del.diffmod {
+ background-color: rgba(248, 81, 73, 0.25);
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins img,
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del img {
+ border: 3px solid;
+ border-radius: 4px;
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins img {
+ border-color: rgba(63, 185, 80, 0.7);
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del img {
+ border-color: rgba(248, 81, 73, 0.7);
+ opacity: 0.6;
+}
+
/* The tint on the note text the assistant was opened on — what "Replace" will hit. */
.ck-content .ck-ai-assistant-target {
background: rgba(148, 112, 219, 0.22);