Skip to content

Build your personal knowledge base with Trilium Notes

feat(ai-assistant): diff the response by block before diffing it by word

Elian Doran8b60aaf2f7d7
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
index e975300d12..99fd8e3b4e 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
@@ -320,4 +320,22 @@ describe("buildAiAssistantQuickActions", () => {
expect(action.commandLabel).toBeUndefined();
}
});
+
+ // The actions that answer with a replacement rather than an edit open their review on the
+ // result; everything else lets the diff of the run decide, which is what an unset view means.
+ it("sends the replacements to the result view and leaves the edits to the diff", () => {
+ const reviewViews = new Map(buildAiAssistantQuickActions()
+ .flatMap((group) => group.actions)
+ .map((action) => [action.id, action.reviewView]));
+
+ expect([ ...reviewViews ].filter(([, view]) => view === "result").map(([id]) => id))
+ .toEqual([
+ "summarize", "explain", "continue", "table", "diagram", "actionItems",
+ "translateEnglish", "translateGerman", "translateSpanish", "translateFrench",
+ "translateRomanian", "translateChinese"
+ ]);
+ for (const id of ["fixTypos", "improveWriting", "makeShorter", "professional", "callout"]) {
+ expect(reviewViews.get(id), id).toBeUndefined();
+ }
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
index 66788e776e..c5a329cdaf 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
@@ -81,7 +81,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
* given); prompts stay English — they are instructions to the model, not UI.
*/
export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
- return withIcons([
+ return decorate([
{
id: "edit",
label: t("ai_assistant.group_edit"),
@@ -230,12 +230,34 @@ const ICONS: Record<string, string> = {
// is its own panel holding nothing but languages, so there is nothing to line up against.
};
-/** Hangs {@link ICONS} on the definitions by id, leaving the ids that have none untouched. */
-function withIcons(groups: AiQuickActionGroup[]): AiQuickActionGroup[] {
+/**
+ * The actions whose answer replaces what it was given instead of editing it: a translation, a
+ * summary, a diagram. Their review opens on the result — an inline diff of two texts with nothing
+ * in common says nothing, however well it is rendered, and the answer is what wants reading.
+ *
+ * Only the outright replacements are listed. Everything else lets the run decide for itself, from
+ * how much of the response the differ could align (see `diffAiResponse`) — which is also what
+ * answers for a prompt the user typed, where there is no definition to go on.
+ */
+const REPLACEMENT_GROUPS = new Set(["translate"]);
+const REPLACEMENT_ACTIONS = new Set(["summarize", "explain", "continue", "table", "diagram", "actionItems"]);
+
+/**
+ * Hangs {@link ICONS} and the review view on the definitions by id, leaving the ids that have
+ * neither untouched. Kept out of the definitions themselves so that each stays about what it asks
+ * the model for, and so that one list per concern can be read for completeness.
+ */
+function decorate(groups: AiQuickActionGroup[]): AiQuickActionGroup[] {
return groups.map((group) => ({
...group,
iconClass: ICONS[group.id],
- actions: group.actions.map((action) => ({ ...action, iconClass: ICONS[action.id] }))
+ actions: group.actions.map((action) => ({
+ ...action,
+ iconClass: ICONS[action.id],
+ reviewView: REPLACEMENT_GROUPS.has(group.id) || REPLACEMENT_ACTIONS.has(action.id)
+ ? "result" as const
+ : undefined
+ }))
}));
}
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
new file mode 100644
index 0000000000..a17da0380d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.spec.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+
+import diffAiResponse from "./ai_diff.js";
+
+const ORIGINAL = [
+ "<h2>Backups</h2>",
+ "<p>Trilium keeps a copy of the database every day, every week and every month.</p>",
+ "<p>You can restore one by stopping the application and swapping the file.</p>"
+].join("");
+
+describe("diffAiResponse", () => {
+ it("marks a corrected word inside the paragraph it was corrected in", () => {
+ const corrected = ORIGINAL.replace("swapping the file.", "swapping the file out.");
+ const { html, rewriteRatio } = diffAiResponse(ORIGINAL, corrected);
+
+ // The two untouched blocks come through as they were, and the third carries the mark.
+ expect(html).toContain("<h2>Backups</h2>");
+ expect(html).toContain("<ins class=\"diffins\">");
+ expect(html).not.toContain("diffblock");
+ expect(rewriteRatio).toBe(0);
+ });
+
+ it("shows a paragraph that shares no words as a replacement rather than word by word", () => {
+ const translated = [
+ "<h2>Copii de rezervă</h2>",
+ "<p>Trilium păstrează o copie a bazei de date în fiecare zi, săptămână și lună.</p>",
+ "<p>Poți restaura una oprind aplicația și înlocuind fișierul.</p>"
+ ].join("");
+ const { html, rewriteRatio } = diffAiResponse(ORIGINAL, translated);
+
+ // Each old block struck out whole, with the block that replaced it right after — not the
+ // alternating word pairs a plain word-level diff produces for two unrelated texts.
+ expect(html).toBe([
+ "<del class=\"diffdel diffblock\"><h2>Backups</h2></del>",
+ "<ins class=\"diffins diffblock\"><h2>Copii de rezervă</h2></ins>",
+ "<del class=\"diffdel diffblock\"><p>Trilium keeps a copy of the database every day, every week and every month.</p></del>",
+ "<ins class=\"diffins diffblock\"><p>Trilium păstrează o copie a bazei de date în fiecare zi, săptămână și lună.</p></ins>",
+ "<del class=\"diffdel diffblock\"><p>You can restore one by stopping the application and swapping the file.</p></del>",
+ "<ins class=\"diffins diffblock\"><p>Poți restaura una oprind aplicația și înlocuind fișierul.</p></ins>"
+ ].join(""));
+ // Nothing of the response was an edit, which is what sends the review to the result view.
+ expect(rewriteRatio).toBe(1);
+ });
+
+ it("keeps a restructured block whole instead of interleaving two kinds of markup", () => {
+ const asList = "<ul><li>A daily copy</li><li>A weekly copy</li><li>A monthly copy</li></ul>";
+ const { html } = diffAiResponse("<p>Trilium keeps a daily, weekly and monthly copy.</p>", asList);
+
+ // A `<p>` word-diffed against a `<ul>` comes out with its tags closing in the wrong order.
+ expect(html).toBe(
+ "<del class=\"diffdel diffblock\"><p>Trilium keeps a daily, weekly and monthly copy.</p></del>"
+ + `<ins class="diffins diffblock">${asList}</ins>`
+ );
+ });
+
+ 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);
+
+ expect(html).toContain("<ins class=\"diffins diffblock\"><p>The copies live next to the database file.</p></ins>");
+ expect(html).not.toContain("diffdel");
+ // An insertion is readable as a diff however large it is, so it is not a rewrite.
+ expect(rewriteRatio).toBe(0);
+ });
+
+ it("renders an unchanged block in the shape the response gave it", () => {
+ const { html } = diffAiResponse(
+ "<p>Never edit the database while the app runs.</p>",
+ "<blockquote class=\"admonition warning\"><p>Never edit the database while the app runs.</p></blockquote>"
+ );
+
+ expect(html).toBe("<blockquote class=\"admonition warning\"><p>Never edit the database while the app runs.</p></blockquote>");
+ });
+
+ it("diffs a selection made inside a paragraph, which has no blocks at all", () => {
+ const { html } = diffAiResponse("the quick <strong>brown</strong> fox", "the quick <strong>red</strong> fox");
+
+ expect(html).toContain("brown");
+ expect(html).toContain("red");
+ expect(html).not.toContain("diffblock");
+ });
+
+ it("treats a response with nothing to align against as entirely rewritten", () => {
+ expect(diffAiResponse("", "<p>generated</p>").rewriteRatio).toBe(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/ai_diff.ts b/apps/client/src/widgets/type_widgets/text/ai_diff.ts
new file mode 100644
index 0000000000..b569866ebb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/ai_diff.ts
@@ -0,0 +1,236 @@
+import type { AiDiffResult } from "@triliumnext/ckeditor5";
+import { diffArrays } from "diff";
+import HtmlDiff from "htmldiff-js";
+
+import { escapeHtml } from "../../../services/utils.js";
+
+/**
+ * The "Changes" view of the AI assistant's review: the response marked up against the content it
+ * would replace.
+ *
+ * A word-level HTML diff — `htmldiff-js` on the two fragments, which is what the revisions dialog
+ * shows — is the right tool only while both sides are recognisably the same text. It aligns on the
+ * longest common runs of words, so a corrected typo or a tightened sentence comes out as a precise
+ * mark on an otherwise readable paragraph. Give it a translation, or any rewrite that keeps the
+ * meaning and none of the words, and the longest common runs are single words like "a" and "de":
+ * the paragraph shreds into dozens of alternating `<del>`/`<ins>` pairs that read as neither the
+ * old text nor the new one.
+ *
+ * So the alignment happens a level up first. Both sides are cut into top-level blocks and matched
+ * against each other; only a pair that is still the same block — same container, and enough words
+ * in common — is handed to the word differ. 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.
+ *
+ * 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
+ * changes at all — a translation scores 1 and is shown as the plain result instead.
+ */
+export default function diffAiResponse(oldHtml: string, newHtml: string): AiDiffResult {
+ const oldBlocks = splitIntoBlocks(oldHtml);
+ const newBlocks = splitIntoBlocks(newHtml);
+
+ // Nothing to align against, so the whole of whichever side exists is the change.
+ if (!oldBlocks.length || !newBlocks.length) {
+ return { html: HtmlDiff.execute(oldHtml, newHtml), rewriteRatio: 1 };
+ }
+
+ const chunks: string[] = [];
+ /** Text length of the response that came out as a replacement rather than as an edit. */
+ let rewrittenLength = 0;
+ let removed: Block[] = [];
+ let added: Block[] = [];
+
+ // Pairs up the blocks between two anchors positionally: the model rewrote the first paragraph
+ // into the first, the second into the second. Where the counts differ the extras are pure
+ // insertions or deletions, which is also what a split or merged paragraph degrades to.
+ function flushPending() {
+ for (let index = 0; index < Math.max(removed.length, added.length); index++) {
+ const before = index < removed.length ? removed[index] : null;
+ const after = index < added.length ? added[index] : null;
+
+ if (before && after) {
+ if (isSameBlockRewritten(before, after)) {
+ chunks.push(HtmlDiff.execute(before.html, after.html));
+ } else {
+ chunks.push(markBlock("del", before), markBlock("ins", after));
+ rewrittenLength += after.text.length;
+ }
+ } else if (before) {
+ chunks.push(markBlock("del", before));
+ } else if (after) {
+ chunks.push(markBlock("ins", after));
+ }
+ }
+ removed = [];
+ added = [];
+ }
+
+ for (const part of diffArrays(oldBlocks, newBlocks, { comparator: isUnchangedBlock })) {
+ if (part.removed) {
+ removed = removed.concat(part.value);
+ } else if (part.added) {
+ added = added.concat(part.value);
+ } else {
+ flushPending();
+ // An unchanged block is emitted in the shape the *response* gave it, so that the two
+ // views show the same content and a rewrapped paragraph (a callout, a collapsible)
+ // still renders as one.
+ chunks.push(...part.value.map((block) => block.html));
+ }
+ }
+ flushPending();
+
+ const responseLength = newBlocks.reduce((total, block) => total + block.text.length, 0);
+ return {
+ html: chunks.join(""),
+ rewriteRatio: responseLength ? rewrittenLength / responseLength : 0
+ };
+}
+
+/**
+ * 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
+ * as a replacement instead — which is what a translation or a heavy rewrite is.
+ */
+const INLINE_DIFF_SIMILARITY = 0.4;
+
+/** 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. */
+ html: string;
+ /** Its container's tag name, or the empty string for a run of loose inline content. */
+ tag: string;
+ /** Its text, whitespace-collapsed — what similarity and equality are measured over. */
+ text: string;
+}
+
+/**
+ * The elements that stand on their own in note content. Anything else at the top level (bare text,
+ * `<strong>`, an inline image — what a selection inside a paragraph stringifies to) is inline, and
+ * consecutive inline nodes are gathered into one block so that a phrase is diffed as a phrase.
+ */
+const BLOCK_TAGS = new Set([
+ "ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "DETAILS", "DIV", "DL", "FIGURE", "FOOTER",
+ "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HR", "MAIN", "NAV", "OL", "P", "PRE",
+ "SECTION", "TABLE", "UL"
+]);
+
+/**
+ * Cuts a fragment into blocks. Parsed with `DOMParser` rather than through an element's
+ * `innerHTML`: the document it builds is inert, so nothing in a model's response loads or runs on
+ * the way past.
+ */
+function splitIntoBlocks(html: string): Block[] {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ const blocks: Block[] = [];
+ let inline: ChildNode[] = [];
+
+ function flushInline() {
+ if (inline.length) {
+ blocks.push({
+ html: inline.map(serialize).join(""),
+ tag: "",
+ text: normalize(inline.map((node) => node.textContent).join(" "))
+ });
+ inline = [];
+ }
+ }
+
+ for (const node of Array.from(doc.body.childNodes)) {
+ const element = node.nodeType === Node.ELEMENT_NODE ? (node as Element) : null;
+
+ if (element && BLOCK_TAGS.has(element.tagName)) {
+ flushInline();
+ blocks.push({ html: element.outerHTML, tag: element.tagName, text: normalize(node.textContent) });
+ } else if (element || node.textContent?.trim() || inline.length) {
+ // Whitespace between two blocks is formatting rather than content, so it starts
+ // nothing — but once a run is open, the space between two inline elements is part of
+ // the text and has to stay.
+ inline.push(node);
+ }
+ }
+
+ flushInline();
+ return blocks;
+}
+
+/** A node as it will appear in the diff. A bare text node is content, not markup, so it escapes. */
+function serialize(node: ChildNode): string {
+ return node.nodeType === Node.ELEMENT_NODE
+ ? (node as Element).outerHTML
+ : escapeHtml(node.textContent ?? "");
+}
+
+/**
+ * Whether the response left a block alone. Compared by text rather than by markup, so a paragraph
+ * the model wrapped in a callout or a collapsible is still recognised as the same paragraph — the
+ * wrapper is visible in the block that gets rendered, and marking every word of an untouched
+ * sentence to announce it would bury the wording changes the reader is looking for.
+ */
+function isUnchangedBlock(left: Block, right: Block): boolean {
+ return left.text ? left.text === right.text : left.html === right.html;
+}
+
+/**
+ * Whether a pair is the same block reworded — the case the word differ handles well — rather than
+ * one block replaced by another.
+ *
+ * The containers have to match, and not only because a paragraph turned into a list is a
+ * structural change rather than a reworded one: `htmldiff-js` interleaves the two markup streams,
+ * so diffing a `<p>` against a `<ul>` emits tags that close in the wrong order, and the preview's
+ * parser then puts the mess back together in whatever shape it likes.
+ */
+function isSameBlockRewritten(before: Block, after: Block): boolean {
+ return before.tag === after.tag && similarity(before, after) >= INLINE_DIFF_SIMILARITY;
+}
+
+/**
+ * How much two blocks have in common, from 0 to 1: the Sørensen–Dice coefficient over their words,
+ * counting repeats, which is cheap and cares about neither word order nor markup.
+ */
+function similarity(before: Block, after: Block): number {
+ if (before.text === after.text) {
+ return before.text || before.html === after.html ? 1 : 0;
+ }
+
+ const beforeWords = tokenize(before.text);
+ const afterWords = tokenize(after.text);
+ if (!beforeWords.length || !afterWords.length) {
+ return 0;
+ }
+
+ const remaining = new Map<string, number>();
+ for (const word of beforeWords) {
+ remaining.set(word, (remaining.get(word) ?? 0) + 1);
+ }
+
+ let common = 0;
+ for (const word of afterWords) {
+ const count = remaining.get(word) ?? 0;
+ if (count) {
+ remaining.set(word, count - 1);
+ common++;
+ }
+ }
+
+ return (2 * common) / (beforeWords.length + afterWords.length);
+}
+
+/**
+ * Wraps a whole block in an insertion or deletion mark. `<ins>`/`<del>` are transparent elements,
+ * so they may hold a block; the `diffblock` class is what tells the preview's stylesheet to draw
+ * this one as a replaced paragraph rather than as a few struck-through words.
+ */
+function markBlock(mark: "ins" | "del", block: Block): string {
+ const kind = mark === "ins" ? "diffins" : "diffdel";
+ return `<${mark} class="${kind} diffblock">${block.html}</${mark}>`;
+}
+
+function tokenize(text: string): string[] {
+ return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
+}
+
+function normalize(text: string | null): string {
+ return (text ?? "").replace(/\s+/g, " ").trim();
+}
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 3e461d5764..6a4de45feb 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,7 +1,6 @@
import { type EditorConfig, getCkLocale, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
-import HtmlDiff from "htmldiff-js";
import i18next from "i18next";
import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";
@@ -18,6 +17,7 @@ import { isMac } from "../../../services/utils.js";
import { resolveContentLanguage } from "../../../utils/formatters.js";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";
import buildAiAssistantStream, { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
+import diffAiResponse from "./ai_diff.js";
import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";
import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";
import { buildToolbarConfig } from "./toolbar.js";
@@ -194,9 +194,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
aiAssistant: {
// `undefined` when no LLM provider is configured, which disables the feature.
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),
+ // The "Changes" review view: a block-aware inline diff, so that a response which
+ // rewrote a paragraph rather than editing it reads as a replacement instead of as
+ // shredded `<ins>`/`<del>` pairs.
+ diff: diffAiResponse,
quickActions: buildAiAssistantQuickActions(),
// The model's HTML reaches the preview through `innerHTML`, so it gets the same
// DOMPurify pass as any other untrusted content rendered outside the editor's
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 0b6b7266d5..e37cc17307 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -17,7 +17,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, AiCompletionUsage, AiDiffFunction, AiQuickAction, AiQuickActionGroup, AiSanitizeFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiDiffResult, AiQuickAction, AiQuickActionGroup, AiReviewView, AiSanitizeFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
export { default as getCkLocale, registerCkTranslations } from "./i18n.js";
export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.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 314667932a..1e51503cc4 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -48,12 +48,32 @@ export type AiStreamFunction = (
signal: AbortSignal
) => Promise<AiCompletionUsage | void>;
+/** Which of the review's two views the preview shows: the plain response, or its diff. */
+export type AiReviewView = "result" | "changes";
+
+/** What a {@link AiDiffFunction} produced, when it has more to say than the diff itself. */
+export interface AiDiffResult {
+ /** The diff, marked up with `<ins>`/`<del>` elements. */
+ html: string;
+ /**
+ * How much of the response — 0 to 1, measured over its text — replaced what it was given
+ * outright instead of editing it in place. Past half the review opens on the plain result:
+ * a diff of two texts with next to nothing in common is noise however well it is rendered,
+ * and the response itself is the thing worth reading.
+ *
+ * Optional; a renderer that does not measure this is treated as having rewritten nothing,
+ * which is the behaviour of a plain word-level diff.
+ */
+ rewriteRatio?: number;
+}
+
/**
* 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).
+ * same mechanism Trilium's revision dialog uses). Returning an {@link AiDiffResult} instead of a
+ * bare string lets the renderer also say how much of the response it could not align.
*/
-export type AiDiffFunction = (oldHtml: string, newHtml: string) => string;
+export type AiDiffFunction = (oldHtml: string, newHtml: string) => string | AiDiffResult;
/**
* A predefined instruction offered in the menu of the toolbar's AI entry — the GPL counterpart of
@@ -86,6 +106,15 @@ export interface AiQuickAction {
* while there is nothing selected and nothing has been generated yet.
*/
requiresContent?: boolean;
+ /**
+ * Which view the review opens on once this action's run finishes. Left unset, how much of the
+ * response the diff could align decides (see {@link AiDiffResult.rewriteRatio}).
+ *
+ * Set it to `"result"` for an action whose answer replaces its source by definition — a
+ * translation, a summary, a diagram — where the diff is two unrelated texts stacked on each
+ * other whatever the measurement says.
+ */
+ reviewView?: AiReviewView;
}
/**
@@ -130,6 +159,9 @@ export interface AiAssistantConfig {
* 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).
+ *
+ * Which of the two views the review opens on follows from what this returns, unless the quick
+ * action that started the run named one itself ({@link AiQuickAction.reviewView}).
*/
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
index d913b337d1..21d463e96c 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
@@ -48,7 +48,7 @@ describe("AiAssistantFormView", () => {
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>", "");
+ form.enterReview({ hasContent: true, diffHtml: "<p><del class=\"diffdel\">old</del><ins class=\"diffins\">new</ins></p>" });
expect(form.phase).toBe("review");
expect(form.hasDiff).toBe(true);
@@ -75,7 +75,7 @@ describe("AiAssistantFormView", () => {
const form = makeForm();
form.beginStreaming();
form.setPreview("<p>generated</p>");
- form.enterReview(true, null, "");
+ form.enterReview({ hasContent: true });
expect(form.phase).toBe("review");
expect(form.hasDiff).toBe(false);
@@ -86,6 +86,22 @@ describe("AiAssistantFormView", () => {
expect(form.tryAgainButtonView.isEnabled).toBe(true);
});
+ it("opens the review on the view the caller names, keeping the other one click away", () => {
+ const form = makeForm();
+ form.beginStreaming();
+ form.setPreview("<p>bonjour</p>");
+ // What a translation's review asks for: its diff is two unrelated texts, not an edit.
+ form.enterReview({ hasContent: true, diffHtml: "<p>diff</p>", viewMode: "result" });
+
+ expect(form.viewMode).toBe("result");
+ expect(previewHtml()).toBe("<p>bonjour</p>");
+ expect(form.hasDiff).toBe(true);
+ expect(form.changesToggleView.isEnabled).toBe(true);
+
+ form.changesToggleView.fire("execute");
+ expect(previewHtml()).toBe("<p>diff</p>");
+ });
+
it("takes the prompt through a placeholder rather than a label, and sends with an icon", () => {
const form = makeForm();
@@ -99,15 +115,36 @@ describe("AiAssistantFormView", () => {
expect(form.sendButtonView.label).toBe("Send");
expect(form.sendButtonView.tooltip).toBe(true);
- // Nothing to send until something is typed, and nothing to send while a run is in flight —
- // where the field goes read-only rather than disabled, so the prompt stays selectable.
+ // Nothing to send until something is typed.
expect(form.sendButtonView.isEnabled).toBe(false);
form.query = "make it shorter";
expect(form.sendButtonView.isEnabled).toBe(true);
+ });
+
+ it("hands the prompt row over to 'Stop' for the length of a run", () => {
+ const form = makeForm();
+
+ expect(form.sendButtonView.isVisible).toBe(true);
+ expect(form.stopButtonView.isVisible).toBe(false);
+ // Both are icons in the same slot, so the row keeps its size as the phase turns over.
+ expect(form.stopButtonView.icon).toContain("<svg");
+ expect(form.stopButtonView.withText).toBe(false);
+ expect(form.stopButtonView.label).toBe("Stop");
+ expect(form.stopButtonView.element?.closest(".ck-ai-assistant-form__prompt-row")).not.toBeNull();
form.beginStreaming();
- expect(form.sendButtonView.isEnabled).toBe(false);
+ expect(form.sendButtonView.isVisible).toBe(false);
+ expect(form.stopButtonView.isVisible).toBe(true);
+
+ // Read-only rather than disabled, so the prompt stays selectable, and the placeholder says
+ // what is happening instead of inviting input that cannot land.
expect(form.promptInputView.isReadOnly).toBe(true);
+ expect(form.promptInputView.placeholder).toBe("Working…");
+
+ // An empty preview stands in for the response until the first chunk arrives, so the dialog
+ // does not read as idle.
+ expect(form.element?.classList.contains("ck-ai-assistant-form_streaming")).toBe(true);
+ expect(previewHtml()).toBe("");
});
it("offers 'Try again' as an icon in the preview's strip rather than among the commit actions", () => {
@@ -126,7 +163,7 @@ describe("AiAssistantFormView", () => {
form.beginStreaming();
form.setPreview("<p>new</p>");
- form.enterReview(true, null, "");
+ form.enterReview({ hasContent: true });
expect(button.isEnabled).toBe(true);
});
@@ -136,7 +173,7 @@ describe("AiAssistantFormView", () => {
form.beginStreaming();
form.setPreview("<p>new</p>");
- form.enterReview(true, null, "", "some-model · 1,234 tokens · ~$0.0042");
+ form.enterReview({ hasContent: true, usageText: "some-model · 1,234 tokens · ~$0.0042" });
expect(form.usageText).toBe("some-model · 1,234 tokens · ~$0.0042");
expect(usageEl?.textContent).toBe("some-model · 1,234 tokens · ~$0.0042");
expect(usageEl?.classList.contains("ck-hidden")).toBe(false);
@@ -145,14 +182,14 @@ describe("AiAssistantFormView", () => {
form.beginStreaming();
expect(form.usageText).toBe("");
expect(usageEl?.classList.contains("ck-hidden")).toBe(true);
- form.enterReview(false, null, "boom", "ignored — no content to review");
+ form.enterReview({ hasContent: false, errorMessage: "boom", usageText: "ignored — no content to review" });
expect(form.usageText).toBe("");
});
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");
+ form.enterReview({ hasContent: false, errorMessage: "provider unreachable" });
expect(form.phase).toBe("prompt");
expect(form.errorMessage).toBe("provider unreachable");
@@ -162,7 +199,7 @@ describe("AiAssistantFormView", () => {
const form = makeForm();
form.beginStreaming();
form.setPreview("<p>new</p>");
- form.enterReview(true, "<p>diff</p>", "");
+ form.enterReview({ hasContent: true, diffHtml: "<p>diff</p>" });
form.reset();
expect(form.phase).toBe("prompt");
@@ -172,7 +209,7 @@ describe("AiAssistantFormView", () => {
// A later streaming run must not resurrect the previous run's diff.
form.beginStreaming();
- form.enterReview(true, null, "");
+ form.enterReview({ hasContent: true });
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 392cd305b2..f85d7f5fa8 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -1,4 +1,4 @@
-import { IconArrowUp, IconRefresh } from "@ckeditor/ckeditor5-icons";
+import { IconArrowUp, IconRefresh, IconStop } from "@ckeditor/ckeditor5-icons";
import {
ButtonView,
FocusCycler,
@@ -12,6 +12,8 @@ import {
type Locale
} from "ckeditor5";
+import type { AiReviewView } from "./ai_assistant_config.js";
+
/**
* Where the form is in its lifecycle: taking a prompt, streaming a response into the preview, or
* showing a finished response for review (Replace / Insert below / Try again). The prompt row stays
@@ -19,8 +21,19 @@ import {
*/
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";
+/** What a finished run leaves the form showing. */
+export interface AiReviewOptions {
+ /** Whether the run produced anything at all; without it the form falls back to the prompt. */
+ hasContent: boolean;
+ /** The (sanitized) diff of the response against what it would replace, when there is one. */
+ diffHtml?: string | null;
+ /** A transport/provider failure to surface; empty when the run succeeded. */
+ errorMessage?: string;
+ /** The run's cost line ("model · tokens · price"). */
+ usageText?: string;
+ /** Which view to open on. Defaults to "changes" whenever there is a diff to show. */
+ viewMode?: AiReviewView;
+}
/**
* The AI assistant dialog's contents: a prompt row, a read-only streaming preview styled like note
@@ -37,7 +50,7 @@ export default class AiAssistantFormView extends View {
/** 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;
+ declare public viewMode: AiReviewView;
/** Whether the current review has a diff to offer; controls the view-mode toggle. */
declare public hasDiff: boolean;
/** The run's cost line ("model · tokens · price"), shown in the review actions row. */
@@ -86,7 +99,12 @@ export default class AiAssistantFormView extends View {
this.previewView = new AiPreviewView(locale);
this.previewView.bind("isVisible").to(this, "phase", (phase) => phase !== "prompt");
+ // 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
+ // from resizing as the phase turns over.
this.stopButtonView = this._createActionButton(locale, t("Stop"), "streaming", "stop");
+ this.stopButtonView.set({ icon: IconStop, withText: false, tooltip: true });
+ this.stopButtonView.class = "ck-button-action ck-ai-assistant-form__icon-action";
this.replaceButtonView = this._createActionButton(locale, t("Replace"), "review", "replace");
this.replaceButtonView.class = "ck-button-action";
this.insertBelowButtonView = this._createActionButton(locale, t("Insert below"), "review", "insertBelow");
@@ -109,7 +127,13 @@ export default class AiAssistantFormView extends View {
this.setTemplate({
tag: "form",
attributes: {
- class: ["ck", "ck-ai-assistant-form"],
+ class: [
+ "ck",
+ "ck-ai-assistant-form",
+ // Lets the stylesheet stand a placeholder in for the response that has been
+ // asked for and not yet begun to arrive.
+ bind.if("phase", "ck-ai-assistant-form_streaming", (phase) => phase === "streaming")
+ ],
tabindex: "-1"
},
children: [
@@ -165,13 +189,14 @@ export default class AiAssistantFormView extends View {
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },
- children: [this.promptInputView, this.sendButtonView]
+ // Send and Stop share the slot at the end of the row; the phase decides which
+ // of the two is on show.
+ children: [this.promptInputView, this.sendButtonView, this.stopButtonView]
},
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__actions"] },
children: [
- this.stopButtonView,
// The row is pushed to the end, so "Replace" comes last to land where the
// eye finishes and the primary action is expected.
this.insertBelowButtonView,
@@ -261,16 +286,16 @@ export default class AiAssistantFormView extends View {
}
/**
- * 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.
+ * Leaves the streaming phase. With content the form enters review, on the view the caller asks
+ * 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: boolean, diffHtml: string | null, errorMessage: string, usageText = ""): void {
+ public enterReview({ hasContent, diffHtml, errorMessage = "", usageText = "", viewMode }: AiReviewOptions): void {
this.phase = hasContent ? "review" : "prompt";
this.errorMessage = errorMessage;
this._diffHtml = diffHtml ?? "";
this.hasDiff = hasContent && !!this._diffHtml;
- this.viewMode = this.hasDiff ? "changes" : "result";
+ this.viewMode = this.hasDiff ? (viewMode ?? "changes") : "result";
this.usageText = hasContent ? usageText : "";
this._renderPreview();
}
@@ -285,7 +310,7 @@ export default class AiAssistantFormView extends View {
}
/** 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) {
+ private _createViewModeButton(locale: Locale, label: string, mode: AiReviewView) {
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);
@@ -306,12 +331,15 @@ export default class AiAssistantFormView extends View {
const t = locale.t;
const input = new InputTextView(locale);
- input.set({
- placeholder: t("Describe a change then press Enter"),
- // A placeholder is not a label, and the field no longer has a visible one, so the
- // accessible name has to be given outright.
- ariaLabel: t("Ask AI to…")
- });
+ // A placeholder is not a label, and the field no longer has a visible one, so the
+ // accessible name has to be given outright.
+ input.set({ ariaLabel: t("Ask AI to…") });
+
+ // The field is read-only mid-run, so an instruction to type would be inviting something
+ // that cannot happen; it says what is happening instead.
+ input.bind("placeholder").to(this, "phase", (phase) => (phase === "streaming"
+ ? t("Working…")
+ : t("Describe a change then press Enter")));
// Two-way: the field drives `query`, and reset() drives the field.
input.bind("value").to(this, "query");
@@ -340,6 +368,8 @@ export default class AiAssistantFormView extends View {
this, "phase",
(query, phase) => !!String(query).trim() && phase !== "streaming"
);
+ // Stands aside for "Stop", which takes over the slot for the length of a run.
+ button.bind("isVisible").to(this, "phase", (phase) => phase !== "streaming");
return button;
}
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 dc03d0219d..6d03de7c56 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
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
import TriliumAiAssistant from "./ai_assistant.js";
-import type { AiCompletionRequest, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./ai_assistant_config.js";
+import type { AiCompletionRequest, AiDiffFunction, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./ai_assistant_config.js";
import AiAssistantUI from "./ai_assistant_ui.js";
// ---- Typed views of the dropdown internals ----
@@ -139,6 +139,9 @@ function dialogTitle(editor: ClassicEditor) {
function openForm(editor: ClassicEditor) {
return editor.plugins.get(Dialog).view?.contentView?.children.get(0) as unknown as {
query: string;
+ phase: string;
+ viewMode: string;
+ hasDiff: boolean;
fire(event: string): void;
};
}
@@ -361,6 +364,53 @@ describe("AiAssistantUI toolbar entry", () => {
});
});
+ describe("the view a finished review opens on", () => {
+ const REVIEW_ACTIONS: AiQuickActionGroup[] = [
+ {
+ id: "edit",
+ label: "Edit or review",
+ actions: [
+ { id: "fixTypos", label: "Fix typos", prompt: "Fix all mistakes." },
+ // A replacement by definition, whatever the diff makes of it.
+ { id: "translate", label: "Translate", prompt: "Translate it.", reviewView: "result" }
+ ]
+ }
+ ];
+
+ /** Runs one quick action against a selection and hands back the form in its review. */
+ async function review(diff: AiDiffFunction, actionId: string) {
+ const stub = createStreamStub();
+ const editor = await createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {
+ aiAssistant: { sanitizeHtml, quickActions: REVIEW_ACTIONS, stream: stub.stream, diff }
+ });
+ const dropdown = createComponent(editor);
+
+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");
+ quickActionButtons(dropdown).find((button) => button.id === actionId)?.fire("execute");
+ await vi.waitFor(() => expect(stub.requests).toHaveLength(1));
+
+ const form = openForm(editor);
+ await vi.waitFor(() => expect(form.phase).toBe("review"));
+ return form;
+ }
+
+ it("is the changes by default, and the result for an action that asks for it", async () => {
+ const diff = () => "<ins>done</ins>";
+
+ expect((await review(diff, "fixTypos")).viewMode).toBe("changes");
+ expect((await review(diff, "translate")).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");
+
+ expect(form.viewMode).toBe("result");
+ // Still offered, only not opened on.
+ expect(form.hasDiff).toBe(true);
+ });
+ });
+
it("is disabled when no LLM provider is configured", async () => {
const editor = await createEditor(QUICK_ACTIONS);
expect(createComponent(editor).isEnabled).toBe(false);
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 e43cab4f52..4ed4c56917 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -17,7 +17,7 @@ import {
type ModelRange
} from "ckeditor5";
-import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup } from "./ai_assistant_config.js";
+import type { AiCompletionUsage, AiDiffResult, AiQuickAction, AiQuickActionGroup, AiReviewView } from "./ai_assistant_config.js";
import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
import AiAssistantFormView from "./ai_assistant_form.js";
import aiIcon from "./theme/icons/ai.svg?raw";
@@ -32,6 +32,14 @@ const RENDER_THROTTLE_MS = 80;
/** Identifies our dialog in the editor-wide `Dialog` plugin, which shows one dialog at a time. */
const DIALOG_ID = "aiAssistant";
+/**
+ * How much of a response has to be a replacement rather than an edit (see
+ * `AiDiffResult.rewriteRatio`) before the review opens on the plain result instead of the diff.
+ * Half is the point where the "Changes" view stops being a set of marks on a text one can still
+ * read and becomes two texts stacked on each other.
+ */
+const REWRITE_RATIO_THRESHOLD = 0.5;
+
/**
* The AI assistant's UI and orchestration: the toolbar entry (a split button whose menu holds the
* host's quick actions), the dialog form, and the stream-preview-commit lifecycle.
@@ -79,6 +87,11 @@ export default class AiAssistantUI extends Plugin {
/** The context of the last run, restored by "Try again" so a retry does not chain on itself. */
private _previousContext = "";
private _lastQuery = "";
+ /**
+ * The view the running quick action asked its review to open on, when it named one. Null for a
+ * typed prompt, which leaves the choice to the diff.
+ */
+ private _reviewView: AiReviewView | null = null;
public init(): void {
const editor = this.editor;
@@ -246,6 +259,7 @@ export default class AiAssistantUI extends Plugin {
// Titled the way the `/` palette names the action: a bare label can be a fragment
// ("Romanian") that only reads as an instruction beside its group heading.
this._open(true, action.commandLabel ?? action.label);
+ this._reviewView = action.reviewView ?? null;
void this._run(action.prompt);
}
@@ -333,8 +347,9 @@ export default class AiAssistantUI extends Plugin {
if (query) {
form.query = "";
// A typed follow-up is no longer the quick action that opened the assistant, so
- // the header stops claiming to be one.
+ // the header stops claiming to be one — and its review view goes with it.
this._setTitle(editor.t("AI assistant"));
+ this._reviewView = null;
void this._run(query);
}
});
@@ -419,7 +434,27 @@ export default class AiAssistantUI extends Plugin {
}
// A response counts as content, so content-requiring quick actions unlock for chaining.
this._updateHasContext();
- form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage, this._formatUsage(usage));
+
+ const diff = this._buildDiff();
+ form.enterReview({
+ hasContent: !!this._cumulative,
+ diffHtml: diff?.html,
+ errorMessage,
+ usageText: this._formatUsage(usage),
+ viewMode: this._resolveReviewView(diff)
+ });
+ }
+
+ /**
+ * Which view the finished run opens on: whatever the quick action asked for, and otherwise
+ * what the diff makes of the response — a rewrite the differ could barely align is shown as
+ * the result, since the marks would outnumber the text they are on.
+ */
+ private _resolveReviewView(diff: AiDiffResult | null): AiReviewView {
+ if (this._reviewView) {
+ return this._reviewView;
+ }
+ return (diff?.rewriteRatio ?? 0) > REWRITE_RATIO_THRESHOLD ? "result" : "changes";
}
/**
@@ -467,13 +502,16 @@ export default class AiAssistantUI extends Plugin {
* 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 {
+ private _buildDiff(): AiDiffResult | null {
const diff = this.editor.config.get("aiAssistant")?.diff;
if (!diff || !this._cumulative || !this._previousContext) {
return null;
}
try {
- return this._sanitize(diff(this._previousContext, this._cumulative));
+ // 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 };
} catch (error) {
// A host diff failure only costs the Changes view, never the response itself.
console.warn("AI assistant: diff renderer failed", error);
@@ -551,6 +589,7 @@ export default class AiAssistantUI extends Plugin {
// would leave them enabled over a closed assistant that has nothing to work on.
this._context = "";
this._previousContext = "";
+ this._reviewView = null;
this._updateHasContext();
if (editor.model.markers.has(AI_TARGET_MARKER)) {
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 0d36567119..5a4f3fdda6 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -32,8 +32,15 @@
gap: var(--ck-spacing-medium);
}
+/* The list scrolls, so it also clips: the panel's inline padding moves onto it, leaving a rule
+ drawn across an item's full width room to reach the panel's edges. */
+.ck.ck-dropdown.ck-ai-assistant-quick-actions .ck-dropdown__panel {
+ padding-inline: 0;
+}
+
.ck.ck-dropdown.ck-ai-assistant-quick-actions .ck-dropdown__panel > .ck-list {
max-height: 320px;
+ padding-inline: var(--ck-editor-popup-padding, 0px);
overflow-x: clip;
overflow-y: auto;
}
@@ -59,11 +66,37 @@
}
}
-/* An empty preview is just a hollow frame — collapse it until the first chunk arrives. */
-.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview:empty {
+/* An empty preview is just a hollow frame — collapse it until there is a run to show. */
+.ck.ck-ai-assistant-form:not(.ck-ai-assistant-form_streaming) .ck-ai-assistant-form__preview:empty {
display: none;
}
+/* Between asking and the first chunk there is nothing to render, and a blank dialog reads as an
+ idle one. Stand in three pulsing lines where the response will land. */
+.ck.ck-ai-assistant-form_streaming .ck-ai-assistant-form__preview:empty {
+ min-height: 4.4em;
+ background-image:
+ linear-gradient(var(--ck-color-base-border) 0 0),
+ linear-gradient(var(--ck-color-base-border) 0 0),
+ linear-gradient(var(--ck-color-base-border) 0 0);
+ background-repeat: no-repeat;
+ background-size: 100% 0.8em, 90% 0.8em, 55% 0.8em;
+ background-position: 0 0.2em, 0 1.7em, 0 3.2em;
+ animation: ck-ai-assistant-pending 1.4s ease-in-out infinite;
+}
+
+@keyframes ck-ai-assistant-pending {
+ 0%, 100% { opacity: 0.3; }
+ 50% { opacity: 0.65; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ck.ck-ai-assistant-form_streaming .ck-ai-assistant-form__preview:empty {
+ animation: none;
+ opacity: 0.45;
+ }
+}
+
.ck.ck-ai-assistant-form .ck-ai-assistant-form__error {
color: var(--ck-color-base-error);
}
@@ -107,6 +140,31 @@
background-color: rgba(248, 81, 73, 0.25);
}
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview .diffblock {
+ display: block;
+ border-inline-start: 3px solid;
+ padding-inline-start: var(--ck-spacing-medium);
+ margin-block: var(--ck-spacing-small);
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview del.diffblock {
+ border-color: rgba(248, 81, 73, 0.7);
+ text-decoration: none;
+ opacity: 0.7;
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview ins.diffblock {
+ border-color: rgba(63, 185, 80, 0.7);
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview .diffblock > :first-child {
+ margin-block-start: 0;
+}
+
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview .diffblock > :last-child {
+ margin-block-end: 0;
+}
+
.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;