Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into feature/ai_assistant

Elian Dorancdef6a37a20a
diff --cc apps/client/src/translations/en/translation.json
index e5cbd0f9eb,eb1629b249..cf09de29e9
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@@ -2499,57 -2828,11 +2828,34 @@@
"copy_image_to_clipboard": "Copy image to clipboard"
},
"link": {
- "failed_to_open": "Failed to open link '{{- href}}': {{- message}}",
- "copy_url": "Copy URL"
+ "failed_to_open": "Failed to open link '{{- href}}': {{- message}}"
},
"link_embed": {
- "play_video": "Play video",
- "title": "Link preview",
- "url": "URL",
- "insert": "Insert",
- "display": "Display",
- "mode_inline": "Inline",
- "mode_card": "Card",
- "mode_embed": "Embed",
- "mode_plain": "Plain link",
- "edit_title": "Edit title",
- "title_label": "Title",
- "save": "Save"
+ "play_video": "Play video"
},
+ "ai_assistant": {
- "title": "AI assistant",
- "prompt_label": "Ask AI to…",
- "send": "Send",
- "stop": "Stop",
- "replace": "Replace",
- "insert_below": "Insert below",
- "try_again": "Try again",
- "result": "Result",
- "changes": "Changes",
- "tokens": "tokens",
- "quick_actions": "Quick actions",
+ "group_edit": "Edit or review",
+ "group_generate": "Generate",
+ "group_tone": "Change tone",
+ "group_translate": "Translate",
+ "action_fix_typos": "Fix typos",
+ "action_improve_writing": "Improve writing",
+ "action_make_shorter": "Make shorter",
+ "action_make_longer": "Make longer",
+ "action_simplify": "Simplify language",
+ "action_summarize": "Summarize",
+ "action_continue": "Continue writing",
+ "tone_professional": "Professional",
+ "tone_casual": "Casual",
+ "tone_direct": "Direct",
+ "tone_friendly": "Friendly",
+ "lang_english": "English",
+ "lang_german": "German",
+ "lang_spanish": "Spanish",
+ "lang_french": "French",
+ "lang_romanian": "Romanian",
+ "lang_chinese": "Simplified Chinese"
+ },
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
"open_note_in_new_split": "Open note in a new split",
@@@ -3344,18 -3796,131 +3819,142 @@@
"export-csv-failed": "Failed to export the spreadsheet to CSV."
},
"text-editor": {
- "checkbox-tooltip": "Right-click or press {{- shortcut}} to change state.",
- "checkbox-tooltip-state-label": "Task state:",
- "checkbox-tooltip-state-unknown-suffix": "(missing definition)",
- "collapsible-body-placeholder": "Type the content here...",
- "collapsible-button-label": "Collapsible block",
- "collapsible-handle-tooltip": "Drag to reposition the collapsible block",
- "collapsible-select-label": "Select collapsible block",
- "collapsible-title-placeholder": "Summary",
- "collapsible-toggle-label": "Toggle collapsible block",
- "collapsible-tooltip": "Click on the arrow or press {{- shortcut}} to collapse/expand.",
- "edit-states-tooltip": "Edit task states",
- "unknown-task-state": "Undefined custom task state",
+ "ck": {
+ "admonition": "Admonition",
++ "ai-assistant": "AI assistant",
+ "align-text-to-the-center": "Align text to the center",
+ "align-text-to-the-left": "Align text to the left",
+ "align-text-to-the-right": "Align text to the right",
+ "anchor": "Anchor",
+ "anchor-name": "Anchor name",
+ "anchor-name-already-exists": "Anchor name already exists.",
+ "anchor-name-cannot-contain-space-characters": "Anchor name cannot contain space characters.",
+ "anchor-name-must-not-be-empty": "Anchor name must not be empty.",
+ "anchor-toolbar": "Anchor toolbar",
+ "anchor-widget": "anchor widget",
+ "anchors": "Anchors",
++ "ask-ai-to": "Ask AI to…",
++ "ask-ai-to-rewrite-the-selection-or-generate-new-content": "Ask AI to rewrite the selection or generate new content.",
+ "box-size": "Box size",
+ "bulleted-list": "Bulleted list",
+ "card": "Card",
+ "caution": "Caution",
++ "changes": "Changes",
+ "click-on-the-arrow-or-press-0-to-collapse-expand": "Click on the arrow or press %0 to collapse/expand.",
+ "collapsible-block": "Collapsible block",
+ "copy-anchor-reference-link": "Copy anchor reference link",
+ "copy-formatting": "Copy formatting",
+ "copy-image-to-clipboard": "Copy image to clipboard",
+ "copy-to-clipboard": "Copy to clipboard",
+ "copy-url": "Copy URL",
+ "create-a-bulleted-list": "Create a bulleted list",
+ "create-a-new-footnote-and-reference-it-here": "Create a new footnote and reference it here",
+ "create-a-numbered-list": "Create a numbered list",
+ "create-a-to-do-list": "Create a to-do list",
+ "cut-selection-into-a-sub-note": "Cut selection into a sub-note",
+ "decrease-the-indentation-of-the-current-block": "Decrease the indentation of the current block.",
+ "display": "Display",
+ "display-mode": "Display mode",
+ "display-the-content-of-another-note-in-this-note": "Display the content of another note in this note",
+ "download-image": "Download image",
+ "drag-to-reposition-the-collapsible-block": "Drag to reposition the collapsible block",
+ "edit-anchor": "Edit anchor",
+ "edit-task-states": "Edit task states",
+ "edit-title": "Edit title",
+ "embed": "Embed",
+ "enter-the-anchor-name-without-spaces": "Enter the anchor name without spaces.",
+ "equation-preview": "Equation preview",
+ "error-rendering-equation": "Error rendering equation",
+ "expandable": "Expandable",
+ "footnote": "Footnote",
+ "footnote-widget": "footnote widget",
+ "full": "Full",
+ "import-markdown-from-the-clipboard": "Import Markdown from the clipboard",
+ "important": "Important",
+ "include-note": "Include note",
+ "include-note-widget": "include note widget",
+ "increase-the-indentation-of-the-current-block": "Increase the indentation of the current block.",
+ "indent": "Indent",
+ "inline": "Inline",
+ "insert-a-0-mermaid-diagram-template": "Insert a \"%0\" Mermaid diagram template",
+ "insert-a-block-of-preformatted-code": "Insert a block of preformatted code.",
+ "insert-a-horizontal-rule": "Insert a horizontal rule.",
+ "insert-a-link-to-another-trilium-note": "Insert a link to another Trilium note",
+ "insert-a-math-equation": "Insert a math equation",
+ "insert-a-new-admonition": "Insert a new admonition",
+ "insert-a-page-break-for-printing": "Insert a page break (for printing)",
+ "insert-a-table": "Insert a table.",
+ "insert-a-toggleable-section-that-hides-shows-content-on-click": "Insert a toggleable section that hides/shows content on click.",
+ "insert-an-anchor-for-internal-linking": "Insert an anchor for internal linking",
+ "insert-an-empty-mermaid-diagram": "Insert an empty Mermaid diagram",
++ "insert-below": "Insert below",
+ "insert-date-time": "Insert date/time",
+ "insert-footnote-0": "Insert footnote %0",
+ "insert-math": "Insert math",
+ "insert-mermaid-diagram": "Insert Mermaid diagram",
+ "insert-mermaid-source-code": "Insert Mermaid source code",
+ "insert-paragraph-after-code-block": "Insert paragraph after code block",
+ "insert-paragraph-before-code-block": "Insert paragraph before code block",
+ "insert-text-snippet": "Insert text snippet",
+ "insert-the-current-date-and-time": "Insert the current date and time",
+ "internal-link": "Internal link",
+ "justify-text-alignment": "Justify text alignment",
+ "keyboard-shortcut": "Keyboard shortcut",
+ "latex": "LaTeX",
+ "link-embed-widget": "link embed widget",
+ "link-mention-widget": "link mention widget",
+ "link-preview": "Link preview",
+ "markdown-import": "Markdown import",
+ "markdown-import-from-clipboard": "Markdown import from clipboard",
+ "math-editor-unavailable": "Math editor unavailable",
+ "math-equation": "Math equation",
+ "medium": "Medium",
+ "mermaid-diagram": "Mermaid diagram",
+ "mermaid-diagram-0": "Mermaid diagram: %0",
+ "mermaid-toolbar": "Mermaid toolbar",
+ "mermaid-widget": "Mermaid widget",
+ "missing-definition": "(missing definition)",
+ "new-footnote": "New footnote",
+ "no-anchors-available": "No anchors available.",
+ "no-text-snippets-available": "No text snippets available.",
+ "no-text-snippets-were-found-matching-0": "No text snippets were found matching \"%0\".",
+ "note": "Note",
+ "numbered-list": "Numbered list",
+ "outdent": "Outdent",
+ "plain-link": "Plain link",
+ "preview": "Preview",
++ "quick-actions": "Quick actions",
+ "quote-a-passage-from-another-source": "Quote a passage from another source.",
+ "read-more-about-mermaid-diagram-syntax": "Read more about Mermaid diagram syntax",
+ "remove-anchor": "Remove anchor",
++ "result": "Result",
+ "right-click-or-press-0-to-change-state": "Right-click or press %0 to change state.",
+ "scroll-to-anchor": "Scroll to anchor",
+ "search-text-snippet": "Search text snippet",
+ "select-collapsible-block": "Select collapsible block",
++ "send": "Send",
+ "source-view": "Source view",
+ "split-view": "Split view",
++ "stop": "Stop",
+ "summary": "Summary",
+ "task-state": "Task state:",
+ "text-snippet": "Text snippet",
+ "text-snippets-found-0": "Text snippets found: %0",
+ "the-file-is-too-large-to-be-uploaded-http-413-if-trilium-is-behind-a-reverse-proxy-raise-its-request-body-size-limit": "The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit.",
+ "the-server-responded-with-http-0": "The server responded with HTTP %0.",
+ "tip": "Tip",
+ "title": "Title",
+ "to-do-list": "To-do list",
+ "toggle-collapsible-block": "Toggle collapsible block",
++ "tokens": "tokens",
++ "try-again": "Try again",
+ "turn-the-current-block-into-a-heading": "Turn the current block into a heading.",
+ "turn-the-current-block-into-a-paragraph": "Turn the current block into a paragraph.",
+ "type-the-content-here": "Type the content here...",
+ "undefined-custom-task-state": "Undefined custom task state",
+ "url": "URL",
+ "warning": "Warning"
+ },
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
"task-state-dropped-message_other": "{{count}} custom task state definitions are invalid and were ignored.",
diff --cc apps/client/src/widgets/type_widgets/text/config.ts
index 02d9ef7327,84d255c072..ec45e3a309
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@@ -1,9 -1,9 +1,10 @@@
- import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, SnippetDefinition } from "@triliumnext/ckeditor5";
+ 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, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
+ 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 { copyTextWithToast } from "../../../services/clipboard_ext.js";
+ import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";
import { t } from "../../../services/i18n.js";
import imageService from "../../../services/image.js";
import { getMermaidConfig } from "../../../services/mermaid.js";
@@@ -12,10 -12,17 +13,18 @@@ import noteAutocompleteService, { type
import options from "../../../services/options.js";
import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";
import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";
+ 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 { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";
+ import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";
import { buildToolbarConfig } from "./toolbar.js";
+ /**
+ * The only license key Trilium ever passes to CKEditor. Every premium plugin the editor used has
+ * been replaced by a GPL in-tree one, so there is no commercial license to configure any more.
+ */
export const OPEN_SOURCE_LICENSE_KEY = "GPL";
export interface BuildEditorOptions {
@@@ -182,19 -188,11 +190,19 @@@ export async function buildConfig(opts
snippets: {
definitions: opts.templates
},
+ 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),
+ quickActions: buildAiAssistantQuickActions()
+ },
- htmlSupport: {
- allow: JSON.parse(options.get("allowedHtmlTags"))
- },
+ htmlSupport: buildHtmlSupportConfig(),
removePlugins: getDisabledPlugins(),
- ...await getCkLocale(opts.uiLanguage)
+ // The locale's CKEditor translations, plus the dictionary of Trilium-authored editor
+ // strings resolved through the app's i18n (see `messages.ts` in the ckeditor5 package).
+ ...await getCkLocale(opts.uiLanguage, { englishMessages: getEnglishEditorMessages(), translate: (key) => t(key) })
};
// User-configurable todo task states (from the `_taskStates` hidden subtree).
diff --cc packages/ckeditor5/src/index.ts
index 21a38732d0,4df90b9652..bf60a186b9
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@@ -13,10 -16,8 +16,10 @@@ export type { SlashCommandConfig, Slash
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, 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 { default as getCkLocale, registerCkTranslations } from "./i18n.js";
+ export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";
export * from "./utils.js";
// Import with sideffects to ensure that type augmentations are present.
diff --cc packages/ckeditor5/src/plugins.ts
index fc00db53bd,6a4d5e79db..d947637e77
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@@ -29,13 -33,10 +33,11 @@@ import AutoformatMath from "./plugins/m
import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";
import CopyLinkUrlButton from "./plugins/copy_link_url.js";
import ImageActions from "./plugins/image_actions.js";
+ import ClipboardBareImage from "./plugins/clipboard_bare_image.js";
+ import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";
import TriliumSnippets from "./plugins/snippets/snippets.js";
+import TriliumAiAssistant from "./plugins/ai_assistant/ai_assistant.js";
- // import "@triliumnext/ckeditor5-mermaid/index.css";
- // import "@triliumnext/ckeditor5-admonition/index.css";
- // import "@triliumnext/ckeditor5-footnotes/index.css";
- // import "@triliumnext/ckeditor5-math/index.css";
import CodeBlockToolbar from "./plugins/code_block_toolbar.js";
import CodeBlockLanguageDropdown from "./plugins/code_block_language_dropdown.js";
import CodeBlockInsertParagraph from "./plugins/code_block_insert_paragraph.js";
@@@ -90,8 -91,9 +92,10 @@@ const TRILIUM_PLUGINS: typeof Plugin[]
CopyAnchorLinkButton,
CopyLinkUrlButton,
ImageActions,
+ ClipboardImageEmbed,
+ ClipboardBareImage,
TriliumSnippets,
+ TriliumAiAssistant,
];
/**
diff --cc packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
index cd02bfdde6,0000000000..c60e6f5247
mode 100644,000000..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
@@@ -1,171 -1,0 +1,171 @@@
+import { Locale } from "ckeditor5";
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { AiQuickAction, AiQuickActionGroup } from "./ai_assistant_config.js";
+import type { AiQuickActionEvent } from "./ai_assistant_form.js";
+import AiAssistantFormView from "./ai_assistant_form.js";
+
+let form: AiAssistantFormView;
+
+function makeForm(quickActions: AiQuickActionGroup[] = []): AiAssistantFormView {
- form = new AiAssistantFormView(new Locale(), (_key, fallback) => fallback, quickActions);
++ form = new AiAssistantFormView(new Locale(), quickActions);
+ form.render();
+ return form;
+}
+
+const SAMPLE_ACTIONS: AiQuickActionGroup[] = [{
+ id: "edit",
+ label: "Edit or review",
+ actions: [
+ { id: "fixTypos", label: "Fix typos", prompt: "Fix all mistakes." },
+ { id: "generate", label: "Generate", prompt: "Write something.", requiresContent: false }
+ ]
+}];
+
+/** The rendered quick-action item buttons, in definition order. */
+function quickActionButtons(): HTMLButtonElement[] {
+ form.quickActionsDropdownView.isOpen = true;
+ const panel = form.quickActionsDropdownView.panelView.element;
+ return Array.from(panel?.querySelectorAll("button") ?? []);
+}
+
+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);
+ // Without the reset exemption, the balloon's `.ck-reset_all` nowraps every paragraph.
+ expect(form.previewView.element?.classList.contains("ck-reset_all-excluded")).toBe(true);
+ });
+
+ 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("shows the usage line only for a review that has one, and clears it on the next run", () => {
+ const form = makeForm();
+ const usageEl = form.element?.querySelector(".ck-ai-assistant-form__usage");
+
+ form.beginStreaming();
+ form.setPreview("<p>new</p>");
+ form.enterReview(true, null, "", "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);
+
+ // A failed follow-up run must not keep advertising the previous run's cost.
+ form.beginStreaming();
+ expect(form.usageText).toBe("");
+ expect(usageEl?.classList.contains("ck-hidden")).toBe(true);
+ form.enterReview(false, null, "boom", "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");
+
+ expect(form.phase).toBe("prompt");
+ expect(form.errorMessage).toBe("provider unreachable");
+ });
+
+ it("hides the quick-actions dropdown when no actions are configured", () => {
+ const form = makeForm();
+ expect(form.quickActionsDropdownView.class).toBe("ck-hidden");
+ });
+
+ it("gates content-requiring quick actions on hasContext and fires quickAction on pick", () => {
+ const form = makeForm(SAMPLE_ACTIONS);
+ const picked: AiQuickAction[] = [];
+ form.on<AiQuickActionEvent>("quickAction", (_evt, quickAction) => {
+ picked.push(quickAction);
+ });
+
+ expect(form.quickActionsDropdownView.class).not.toBe("ck-hidden");
+
+ // Opened on an empty selection: "Fix typos" needs content, "Generate" does not.
+ const [fixTypos, generate] = quickActionButtons();
+ expect(fixTypos.classList.contains("ck-disabled")).toBe(true);
+ expect(generate.classList.contains("ck-disabled")).toBe(false);
+
+ fixTypos.click();
+ expect(picked).toHaveLength(0);
+ generate.click();
+ expect(picked.map((quickAction) => quickAction.id)).toEqual(["generate"]);
+
+ // With content (a selection, or a response to chain on) everything unlocks.
+ form.hasContext = true;
+ expect(fixTypos.classList.contains("ck-disabled")).toBe(false);
+ fixTypos.click();
+ expect(picked.map((quickAction) => quickAction.prompt)).toEqual(["Write something.", "Fix all mistakes."]);
+ });
+
+ 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 --cc packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
index 7a11d6c195,0000000000..ac1839598f
mode 100644,000000..100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@@ -1,439 -1,0 +1,438 @@@
+import {
+ addListToDropdown,
+ ButtonView,
+ Collection,
+ createDropdown,
+ createLabeledInputText,
+ FocusCycler,
+ FocusTracker,
+ KeystrokeHandler,
+ LabeledFieldView,
+ submitHandler,
+ View,
+ ViewCollection,
+ ViewModel,
+ type DropdownView,
+ type FocusableView,
+ type InputTextView,
+ type ListDropdownButtonDefinition,
+ type ListDropdownItemDefinition,
+ type Locale
+} from "ckeditor5";
+
+import type { AiQuickAction, AiQuickActionGroup } from "./ai_assistant_config.js";
+
- /** Resolves a translation key, falling back to the given English text. See `translate.ts`. */
- type Translate = (key: string, fallback: string) => string;
-
+/**
+ * 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
+ * usable in the review phase so a follow-up query can chain on the response.
+ */
+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";
+
+/** Fired when the user picks an entry in the "Quick actions" dropdown. */
+export type AiQuickActionEvent = {
+ name: "quickAction";
+ args: [action: AiQuickAction];
+};
+
+/**
+ * The AI assistant balloon: a prompt row, a read-only streaming preview styled like note content,
+ * 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 {
+
+ declare public phase: AiAssistantFormPhase;
+ /** The instruction typed by the user; two-way bound to the input field. */
+ 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 run's cost line ("model · tokens · price"), shown in the review actions row. */
+ declare public usageText: string;
+ /**
+ * Whether there is content for a quick action to work on — the captured selection, or after a
+ * run, the response being chained on. Gates the `requiresContent` quick actions.
+ */
+ declare public hasContext: 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 quickActionsDropdownView: DropdownView;
+ public readonly resultToggleView: ButtonView;
+ public readonly changesToggleView: ButtonView;
+ public readonly previewView: AiPreviewView;
+ public readonly stopButtonView: ButtonView;
+ public readonly replaceButtonView: ButtonView;
+ public readonly insertBelowButtonView: ButtonView;
+ public readonly tryAgainButtonView: ButtonView;
+
+ public readonly focusTracker = new FocusTracker();
+ public readonly keystrokes = new KeystrokeHandler();
+
+ private readonly _focusables = new ViewCollection<FocusableView>();
+ private readonly _focusCycler: FocusCycler;
+
- constructor(locale: Locale, translate: Translate, quickActions: AiQuickActionGroup[] = []) {
++ constructor(locale: Locale, quickActions: AiQuickActionGroup[] = []) {
+ super(locale);
+
++ const t = locale.t;
++
+ this.set("phase", "prompt");
+ this.set("query", "");
+ this.set("errorMessage", "");
+ this.set("viewMode", "result");
+ this.set("hasDiff", false);
+ this.set("usageText", "");
+ this.set("hasContext", 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.quickActionsDropdownView = this._createQuickActionsDropdown(locale, translate, quickActions);
- this.promptInputView = this._createPromptInput(locale, translate);
- this.sendButtonView = this._createSendButton(locale, translate);
++ this.resultToggleView = this._createViewModeButton(locale, t("Result"), "result");
++ this.changesToggleView = this._createViewModeButton(locale, t("Changes"), "changes");
++ this.quickActionsDropdownView = this._createQuickActionsDropdown(locale, quickActions);
++ 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");
+
- this.stopButtonView = this._createActionButton(locale, translate("ai_assistant.stop", "Stop"), "streaming", "stop");
- this.replaceButtonView = this._createActionButton(locale, translate("ai_assistant.replace", "Replace"), "review", "replace");
++ this.stopButtonView = this._createActionButton(locale, t("Stop"), "streaming", "stop");
++ this.replaceButtonView = this._createActionButton(locale, t("Replace"), "review", "replace");
+ this.replaceButtonView.class = "ck-button-action";
- this.insertBelowButtonView = this._createActionButton(locale, translate("ai_assistant.insert_below", "Insert below"), "review", "insertBelow");
- this.tryAgainButtonView = this._createActionButton(locale, translate("ai_assistant.try_again", "Try again"), "review", "tryAgain");
++ this.insertBelowButtonView = this._createActionButton(locale, t("Insert below"), "review", "insertBelow");
++ this.tryAgainButtonView = this._createActionButton(locale, t("Try again"), "review", "tryAgain");
+
+ const bind = this.bindTemplate;
+
+ this.setTemplate({
+ tag: "form",
+ attributes: {
+ class: ["ck", "ck-ai-assistant-form", "ck-responsive-form"],
+ tabindex: "-1"
+ },
+ children: [
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-ai-assistant-form__heading"] },
+ children: [
+ {
+ tag: "span",
+ attributes: { class: ["ck", "ck-ai-assistant-form__title"] },
- children: [{ text: translate("ai_assistant.title", "AI assistant") }]
++ children: [{ text: t("AI assistant") }]
+ },
+ this.resultToggleView,
+ this.changesToggleView
+ ]
+ },
+ this.previewView,
+ {
+ tag: "div",
+ attributes: {
+ class: [
+ "ck",
+ "ck-ai-assistant-form__error",
+ bind.if("errorMessage", "ck-hidden", (message) => !message)
+ ]
+ },
+ children: [{ text: bind.to("errorMessage") }]
+ },
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },
+ children: [this.quickActionsDropdownView, this.promptInputView, this.sendButtonView]
+ },
+ {
+ tag: "div",
+ attributes: { class: ["ck", "ck-ai-assistant-form__actions"] },
+ children: [
+ this.stopButtonView,
+ this.replaceButtonView,
+ this.insertBelowButtonView,
+ this.tryAgainButtonView,
+ {
+ tag: "span",
+ attributes: {
+ class: [
+ "ck",
+ "ck-ai-assistant-form__usage",
+ bind.if("usageText", "ck-hidden", (text) => !text)
+ ]
+ },
+ children: [{ text: bind.to("usageText") }]
+ }
+ ]
+ }
+ ]
+ });
+
+ this._focusCycler = new FocusCycler({
+ focusables: this._focusables,
+ focusTracker: this.focusTracker,
+ keystrokeHandler: this.keystrokes,
+ actions: {
+ focusPrevious: "shift + tab",
+ focusNext: "tab"
+ }
+ });
+ }
+
+ public override render(): void {
+ super.render();
+
+ // Turns a native form submit (the Enter key included) into the view's own `submit` event.
+ submitHandler({ view: this });
+
+ const focusables = [
+ this.resultToggleView,
+ this.changesToggleView,
+ this.quickActionsDropdownView,
+ this.promptInputView,
+ this.sendButtonView,
+ this.stopButtonView,
+ this.replaceButtonView,
+ this.insertBelowButtonView,
+ this.tryAgainButtonView
+ ];
+ for (const view of focusables) {
+ this._focusables.add(view);
+ /* v8 ignore next -- a child view rendered as part of this template always has an element */
+ if (view.element) {
+ this.focusTracker.add(view.element);
+ }
+ }
+
+ /* v8 ignore next -- super.render() has just built this view's element */
+ if (this.element) {
+ this.keystrokes.listenTo(this.element);
+ }
+ }
+
+ public override destroy(): void {
+ super.destroy();
+ this.focusTracker.destroy();
+ this.keystrokes.destroy();
+ }
+
+ /** Puts the form back in its blank prompt state, ready for the next opening. */
+ public reset(): void {
+ this.phase = "prompt";
+ this.query = "";
+ this.errorMessage = "";
+ this._resultHtml = "";
+ this._diffHtml = "";
+ this.hasDiff = false;
+ this.viewMode = "result";
+ this.usageText = "";
+ this._renderPreview();
+ }
+
+ /** Enters the streaming phase with an empty preview. Streaming always shows the raw result. */
+ public beginStreaming(): void {
+ this.phase = "streaming";
+ this.errorMessage = "";
+ this._resultHtml = "";
+ this._diffHtml = "";
+ this.hasDiff = false;
+ this.viewMode = "result";
+ this.usageText = "";
+ this._renderPreview();
+ }
+
+ /** Renders the (sanitized, cumulative) response received so far. */
+ public setPreview(html: string): void {
+ this._resultHtml = html;
+ this._renderPreview();
+ }
+
+ /**
+ * 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 enterReview(hasContent: boolean, diffHtml: string | null, errorMessage: string, usageText = ""): void {
+ this.phase = hasContent ? "review" : "prompt";
+ this.errorMessage = errorMessage;
+ this._diffHtml = diffHtml ?? "";
+ this.hasDiff = hasContent && !!this._diffHtml;
+ this.viewMode = this.hasDiff ? "changes" : "result";
+ this.usageText = hasContent ? usageText : "";
+ 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);
+ }
+
+ /**
+ * The grouped "Quick actions" dropdown. Picking an entry fires `quickAction` with its
+ * {@link AiQuickAction} — the orchestrator runs its prompt as if it had been typed. Actions
+ * marked `requiresContent` are disabled while there is nothing to work on. Hidden entirely
+ * when the host configured no actions.
+ */
- private _createQuickActionsDropdown(locale: Locale, translate: Translate, groups: AiQuickActionGroup[]) {
++ private _createQuickActionsDropdown(locale: Locale, groups: AiQuickActionGroup[]) {
+ const dropdown = createDropdown(locale);
+
+ dropdown.buttonView.set({
- label: translate("ai_assistant.quick_actions", "Quick actions"),
++ label: locale.t("Quick actions"),
+ withText: true
+ });
+ // DropdownView has no `isVisible`; an empty action list hides the component wholesale.
+ if (!groups.length) {
+ dropdown.class = "ck-hidden";
+ }
+ dropdown.bind("isEnabled").to(this, "phase", (phase) => phase !== "streaming");
+
+ const items = new Collection<ListDropdownItemDefinition>();
+ for (const group of groups) {
+ const children = new Collection<ListDropdownButtonDefinition>();
+ for (const action of group.actions) {
+ const definition: ListDropdownButtonDefinition = {
+ type: "button",
+ model: new ViewModel({
+ _quickAction: action,
+ label: action.label,
+ withText: true
+ })
+ };
+ if (action.requiresContent !== false) {
+ definition.model.bind("isEnabled").to(this, "hasContext");
+ }
+ children.add(definition);
+ }
+ items.add({ type: "group", label: group.label, items: children });
+ }
+ addListToDropdown(dropdown, items);
+
+ dropdown.on("execute", (evt) => {
+ this.fire<AiQuickActionEvent>("quickAction", (evt.source as unknown as { _quickAction: AiQuickAction })._quickAction);
+ });
+
+ return dropdown;
+ }
+
+ /** 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) {
++ private _createPromptInput(locale: Locale) {
+ const input = new LabeledFieldView(locale, createLabeledInputText);
- input.label = translate("ai_assistant.prompt_label", "Ask AI to…");
++ input.label = locale.t("Ask AI to…");
+
+ // Two-way: the field drives `query`, and reset() drives the field.
+ input.fieldView.bind("value").to(this, "query");
+ input.fieldView.on("input", () => {
+ /* v8 ignore next -- the input event can only come from a rendered element */
+ this.query = input.fieldView.element?.value ?? "";
+ });
+ input.bind("isEnabled").to(this, "phase", (phase) => phase !== "streaming");
+
+ return input;
+ }
+
- private _createSendButton(locale: Locale, translate: Translate) {
++ private _createSendButton(locale: Locale) {
+ const button = new ButtonView(locale);
+ button.set({
- label: translate("ai_assistant.send", "Send"),
++ label: locale.t("Send"),
+ withText: true,
+ type: "submit",
+ class: "ck-button-action ck-button-bold"
+ });
+ button.bind("isEnabled").to(
+ this, "query",
+ this, "phase",
+ (query, phase) => !!String(query).trim() && phase !== "streaming"
+ );
+ return button;
+ }
+
+ /** A text action button that is only visible in the given phase and re-emits `eventName`. */
+ private _createActionButton(locale: Locale, label: string, phase: AiAssistantFormPhase, eventName: string) {
+ const button = new ButtonView(locale);
+ button.set({ label, withText: true });
+ button.bind("isVisible").to(this, "phase", (currentPhase) => currentPhase === phase);
+ button.on("execute", () => this.fire(eventName));
+ return button;
+ }
+}
+
+/**
+ * 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.
+ *
+ * The content is assigned through `innerHTML` on purpose — the stream delivers a growing HTML
+ * prefix, and the browser's parser auto-closes elements cut off mid-stream, so every tick renders
+ * something sensible without any incremental DOM diffing. Callers sanitize before handing HTML in.
+ */
+class AiPreviewView extends View {
+
+ declare public isVisible: boolean;
+
+ constructor(locale: Locale) {
+ super(locale);
+ this.set("isVisible", false);
+
+ const bind = this.bindTemplate;
+ this.setTemplate({
+ tag: "div",
+ attributes: {
+ class: [
+ "ck",
+ "ck-ai-assistant-form__preview",
+ "ck-content",
+ // Exempt the preview subtree from CKEditor's UI reset — inside the balloon,
+ // `.ck-reset_all` otherwise forces `white-space: nowrap` (plus zeroed margins
+ // and the UI font) onto the content, making every paragraph one long
+ // unwrappable line.
+ "ck-reset_all-excluded",
+ bind.if("isVisible", "ck-hidden", (isVisible) => !isVisible)
+ ]
+ }
+ });
+ }
+
+ public setContent(html: string): void {
+ const element = this.element;
+ /* v8 ignore next -- the preview is only written to after the form has rendered */
+ if (!element) {
+ return;
+ }
+
+ // Follow the stream unless the user has scrolled up to read something.
+ const wasAtBottom = element.scrollTop + element.clientHeight >= element.scrollHeight - 24;
+ element.innerHTML = html;
+ if (wasAtBottom) {
+ element.scrollTop = element.scrollHeight;
+ }
+ }
+}
diff --cc packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index 8d864b3d78,0000000000..260486986b
mode 100644,000000..100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@@ -1,376 -1,0 +1,375 @@@
+import {
+ ButtonView,
+ clickOutsideHandler,
+ ContextualBalloon,
+ Plugin,
+ type ModelNode,
+ type ModelRange
+} from "ckeditor5";
+
- import { translate } from "../translate.js";
+import type { AiCompletionUsage } from "./ai_assistant_config.js";
+import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
+import AiAssistantFormView, { type AiQuickActionEvent } from "./ai_assistant_form.js";
+import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";
+import aiIcon from "./theme/icons/ai.svg?raw";
+import "./theme/ai_assistant.css";
+
+/**
+ * SSE chunks can arrive per-token; re-rendering the whole preview for each one buys nothing
+ * visually and burns CPU re-parsing the growing prefix. One render per interval is smooth enough.
+ */
+const RENDER_THROTTLE_MS = 80;
+
+/**
+ * The AI assistant's UI and orchestration: the toolbar button, the balloon form, and the
+ * stream-preview-commit lifecycle.
+ *
+ * The core design decision is that **the stream never touches the document**. The response
+ * streams into the form's detached preview; the note is modified exactly once, when the user
+ * commits with Replace or Insert below — a single `model.change()`, so a single undo step.
+ */
+export default class AiAssistantUI extends Plugin {
+
+ static get requires() {
+ return [AiAssistantEditing, ContextualBalloon] as const;
+ }
+
+ static get pluginName() {
+ return "AiAssistantUI" as const;
+ }
+
+ private _formView: AiAssistantFormView | null = null;
+ private _abortController: AbortController | null = null;
+ private _streaming = false;
+
+ /** The cumulative response of the current/last run, after fence-stripping. */
+ private _cumulative = "";
+ /** The HTML the next query will run against: the selection, then each committed-to response. */
+ private _context = "";
+ /** The context of the last run, restored by "Try again" so a retry does not chain on itself. */
+ private _previousContext = "";
+ private _lastQuery = "";
+
+ public init(): void {
+ const editor = this.editor;
+
+ editor.ui.componentFactory.add("aiAssistant", (locale) => {
++ const t = locale.t;
+ const command = editor.commands.get("aiAssistant");
+ const buttonView = new ButtonView(locale);
+
+ buttonView.set({
- label: translate(editor, "ai_assistant.title", "AI assistant"),
++ label: t("AI assistant"),
+ icon: aiIcon,
+ tooltip: true
+ });
+
+ /* v8 ignore next -- AiAssistantEditing always registers the command (it is required by this plugin) */
+ if (command) {
+ buttonView.bind("isEnabled").to(command, "isEnabled");
+ }
+
+ this.listenTo(buttonView, "execute", () => editor.execute("aiAssistant"));
+ return buttonView;
+ });
+ }
+
+ public override destroy(): void {
+ super.destroy();
+ this._abortController?.abort();
+ this._formView?.destroy();
+ }
+
+ /** Opens the balloon on the current selection. Invoked by the `aiAssistant` command. */
+ public show(): void {
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = this._getForm();
+
+ if (balloon.hasView(form)) {
+ form.focus();
+ return;
+ }
+
+ // Capture the context and pin the target before focus moves into the balloon and the
+ // document selection stops being trustworthy.
+ const model = editor.model;
+ const selection = model.document.selection;
+ this._context = selection.isCollapsed
+ ? ""
+ : editor.data.stringify(model.getSelectedContent(selection));
+ this._previousContext = this._context;
+ this._cumulative = "";
+ form.hasContext = !!this._context;
+
+ const range = selection.getFirstRange();
+ /* v8 ignore next -- the document selection always has at least one range */
+ if (range) {
+ model.change((writer) => {
+ writer.addMarker(AI_TARGET_MARKER, { range, usingOperation: false, affectsData: false });
+ });
+ }
+
+ form.reset();
+ balloon.add({ view: form, position: this._getBalloonPosition() });
+ form.focus();
+ }
+
+ private _getForm(): AiAssistantFormView {
+ if (this._formView) {
+ return this._formView;
+ }
+
+ const editor = this.editor;
+ const form = new AiAssistantFormView(
+ editor.locale,
- (key, fallback) => translate(editor, key, fallback),
+ editor.config.get("aiAssistant")?.quickActions ?? []
+ );
+ this._formView = form;
+
+ form.on("submit", () => {
+ const query = form.query.trim();
+ if (query) {
+ form.query = "";
+ void this._run(query);
+ }
+ });
+ form.on<AiQuickActionEvent>("quickAction", (_evt, action) => {
+ void this._run(action.prompt);
+ });
+ form.on("stop", () => this._abortController?.abort());
+ form.on("replace", () => this._commit("replace"));
+ form.on("insertBelow", () => this._commit("insertBelow"));
+ form.on("tryAgain", () => {
+ // Retry against what the last run saw, not against its own output.
+ this._context = this._previousContext;
+ 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) => {
+ this._hide();
+ cancel();
+ });
+ clickOutsideHandler({
+ emitter: form,
+ activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),
+ contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],
+ callback: () => {
+ if (form.phase === "prompt" && !this._cumulative) {
+ this._hide();
+ }
+ }
+ });
+
+ return form;
+ }
+
+ private async _run(query: string): Promise<void> {
+ const editor = this.editor;
+ const stream = editor.config.get("aiAssistant")?.stream;
+ const form = this._getForm();
+ /* v8 ignore next -- the command is disabled without a stream, and the form blocks submits while streaming */
+ if (!stream || this._streaming) {
+ return;
+ }
+
+ this._previousContext = this._context;
+ this._lastQuery = query;
+ this._streaming = true;
+ this._cumulative = "";
+ form.beginStreaming();
+
+ const abortController = new AbortController();
+ this._abortController = abortController;
+
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const render = (html: string) => {
+ form.setPreview(sanitizeAiHtml(html));
+ // The preview grows as it fills; keep the balloon anchored rather than overflowing.
+ if (balloon.visibleView === form) {
+ balloon.updatePosition();
+ }
+ };
+
+ let renderTimer: ReturnType<typeof setTimeout> | null = null;
+ let pendingHtml: string | null = null;
+ const onData = (cumulative: string) => {
+ const cleaned = stripMarkdownFences(cumulative);
+ this._cumulative = cleaned;
+ if (renderTimer) {
+ pendingHtml = cleaned;
+ return;
+ }
+ render(cleaned);
+ renderTimer = setTimeout(() => {
+ renderTimer = null;
+ if (pendingHtml !== null) {
+ const html = pendingHtml;
+ pendingHtml = null;
+ render(html);
+ }
+ }, RENDER_THROTTLE_MS);
+ };
+
+ let errorMessage = "";
+ let usage: AiCompletionUsage | null = null;
+ try {
+ usage = (await stream({ query, context: this._context }, onData, abortController.signal)) ?? null;
+ } catch (error) {
+ // An abort is the user's Stop: whatever already streamed stays reviewable.
+ if (!(error instanceof DOMException && error.name === "AbortError")) {
+ errorMessage = error instanceof Error ? error.message : String(error);
+ }
+ } finally {
+ if (renderTimer) {
+ clearTimeout(renderTimer);
+ renderTimer = null;
+ }
+ if (pendingHtml !== null) {
+ render(pendingHtml);
+ }
+ this._streaming = false;
+ this._abortController = null;
+ }
+
+ if (this._cumulative) {
+ // Follow-up queries chain on the response ("now make it shorter"), premium-style.
+ this._context = this._cumulative;
+ }
+ // A response counts as content, so content-requiring quick actions unlock for chaining.
+ form.hasContext = !!this._context;
+ form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage, this._formatUsage(usage));
+ }
+
+ /**
+ * The review's cost line, e.g. `claude-sonnet-5 · 1,234 tokens · ~$0.0042`. Only the fields
+ * the provider reported are shown; an aborted or failed run has none at all.
+ */
+ private _formatUsage(usage: AiCompletionUsage | null): string {
+ if (!usage) {
+ return "";
+ }
+ const parts: string[] = [];
+ if (usage.model) {
+ parts.push(usage.model);
+ }
+ if (usage.totalTokens != null) {
- parts.push(`${usage.totalTokens.toLocaleString()} ${translate(this.editor, "ai_assistant.tokens", "tokens")}`);
++ parts.push(`${usage.totalTokens.toLocaleString()} ${this.editor.t("tokens")}`);
+ }
+ if (usage.cost != null) {
+ // A single completion usually costs well under a cent; two decimals would show $0.00.
+ parts.push(`~$${usage.cost < 0.01 ? usage.cost.toFixed(4) : usage.cost.toFixed(2)}`);
+ }
+ return parts.join(" · ");
+ }
+
+ /**
+ * 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;
+ }
+ }
+
+ /**
+ * The single write to the document: parses the final response through the data pipeline (the
+ * schema drops anything the editor cannot represent) and inserts it at the pinned target.
+ */
+ private _commit(mode: "replace" | "insertBelow"): void {
+ const editor = this.editor;
+ const html = this._cumulative;
+ /* v8 ignore next -- the commit buttons are only visible in the review phase, which requires content */
+ if (!html) {
+ return;
+ }
+
+ const modelFragment = editor.data.toModel(editor.data.processor.toView(sanitizeAiHtml(html)));
+ const model = editor.model;
+
+ model.change((writer) => {
+ const target = this._getTargetRange();
+ if (!target) {
+ return;
+ }
+ if (mode === "replace") {
+ model.insertContent(modelFragment, target);
+ } else {
+ // After the outermost block containing the target's end, so "Insert below" lands
+ // below the whole selection rather than inside it.
+ let block: ModelNode | null = target.end.parent as ModelNode;
+ while (block && block.parent && !block.parent.is("rootElement")) {
+ block = block.parent as ModelNode;
+ }
+ if (block && !block.is("rootElement")) {
+ model.insertContent(modelFragment, writer.createPositionAfter(block));
+ } else {
+ model.insertContent(modelFragment, target.end);
+ }
+ }
+ });
+
+ this._hide();
+ }
+
+ private _getTargetRange(): ModelRange | null {
+ const model = this.editor.model;
+ const marker = model.markers.has(AI_TARGET_MARKER) ? model.markers.get(AI_TARGET_MARKER) : null;
+ return marker?.getRange() ?? model.document.selection.getFirstRange() ?? null;
+ }
+
+ private _hide(): void {
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = this._formView;
+
+ this._abortController?.abort();
+ this._cumulative = "";
+
+ if (editor.model.markers.has(AI_TARGET_MARKER)) {
+ editor.model.change((writer) => writer.removeMarker(AI_TARGET_MARKER));
+ }
+ if (form && balloon.hasView(form)) {
+ balloon.remove(form);
+ }
+ form?.reset();
+ editor.editing.view.focus();
+ }
+
+ private _getBalloonPosition() {
+ const editor = this.editor;
+ return {
+ target: () => {
+ const modelRange = this._getTargetRange();
+ if (modelRange) {
+ const viewRange = editor.editing.mapper.toViewRange(modelRange);
+ return editor.editing.view.domConverter.viewRangeToDom(viewRange);
+ }
+ /* v8 ignore next -- there is always either a marker or a document selection range */
+ return editor.ui.getEditableElement() as HTMLElement;
+ }
+ };
+ }
+}
diff --cc packages/ckeditor5/src/plugins/mention/slash_commands.ts
index 892ac26a6d,dbfc14a2db..cc21aaa302
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@@ -10,13 -15,40 +15,41 @@@ import
IconHeading6,
IconHorizontalLine,
IconIndent,
+ IconNumberedList,
IconOutdent,
+ IconPageBreak,
IconParagraph,
IconQuote,
- IconTable
+ IconTable,
+ IconTodoList
} from "@ckeditor/ckeditor5-icons";
- import { type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";
-
+ import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";
+ import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
+ import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
+ import bxError from "boxicons/svg/regular/bx-error.svg?raw";
+ import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
+ import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
+ import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
+ import { BookmarkUI, type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";
+
+ import collapsibleIcon from "../../icons/collapsible.svg?raw";
+ import dateTimeIcon from "../../icons/date-time.svg?raw";
+ import insertFootnoteIcon from "../../icons/insert-footnote.svg?raw";
+ import importMarkdownIcon from "../../icons/markdown-mark.svg?raw";
+ import mathIcon from "../../icons/math.svg?raw";
+ import noteIcon from "../../icons/note.svg?raw";
+ import internalLinkIcon from "../../icons/trilium.svg?raw";
+ import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admonition_command.js";
+ import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
++import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";
+ import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";
+ import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from "../insert_date_time.js";
+ import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";
+ import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";
+ import MathUI from "../math/math_ui.js";
+ import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";
+ import type { MermaidSample } from "../mermaid/mermaid_ui.js";
+ import SnippetsEditing from "../snippets/snippetsediting.js";
import { registerMentionFeed } from "./register_feed.js";
export const SLASH_MARKER = "/";
@@@ -261,6 -298,241 +299,249 @@@ export function buildDefaultSlashComman
];
}
+ /**
+ * The palette entries for Trilium's own features, plus the handful that replace a CKEditor built-in
+ * whose title or icon Trilium re-authors (the lists, the blank Mermaid diagram).
+ *
+ * These used to be built by the host and injected through `slashCommand.extraCommands`, because
+ * premium `SlashCommand` owned the palette and config was the only way in. Trilium owns it now, so
+ * they are built here like every other group — which is also what lets them use `editor.t()`: the
+ * host translator resolved only Trilium's catalog, leaving strings such as "Align left" and "Page
+ * break" in English even though CKEditor ships translations for them.
+ */
+ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ ...buildListSlashCommands(editor),
+ ...buildAlignmentSlashCommands(editor),
+ ...buildAdmonitionSlashCommands(editor),
+ ...buildMermaidSlashCommands(editor),
++ {
++ id: "ai-assistant",
++ title: t("AI assistant"),
++ description: t("Ask AI to rewrite the selection or generate new content."),
++ aliases: [ "ask ai", "assistant" ],
++ icon: aiIcon,
++ commandName: "aiAssistant"
++ },
+ {
+ id: "collapsible",
+ title: t("Collapsible block"),
+ description: t("Insert a toggleable section that hides/shows content on click."),
+ aliases: [ "details", "fold", "toggle" ],
+ icon: collapsibleIcon,
+ commandName: "collapsible"
+ },
+ {
+ id: "footnote",
+ title: t("Footnote"),
+ description: t("Create a new footnote and reference it here"),
+ icon: insertFootnoteIcon,
+ commandName: "InsertFootnote"
+ },
+ {
+ id: "datetime",
+ title: t("Insert date/time"),
+ description: t("Insert the current date and time"),
+ icon: dateTimeIcon,
+ commandName: INSERT_DATE_TIME_COMMAND
+ },
+ {
+ id: "internal-link",
+ title: t("Internal link"),
+ description: t("Insert a link to another Trilium note"),
+ aliases: [ "internal link", "trilium link", "reference link" ],
+ icon: internalLinkIcon,
+ commandName: INTERNAL_LINK_COMMAND
+ },
+ {
+ id: "math",
+ title: t("Math equation"),
+ description: t("Insert a math equation"),
+ aliases: [ "latex", "equation" ],
+ icon: mathIcon,
+ execute: (target: Editor) => target.plugins.get(MathUI)._showUI()
+ },
+ {
+ id: "include-note",
+ title: t("Include note"),
+ description: t("Display the content of another note in this note"),
+ icon: noteIcon,
+ commandName: INCLUDE_NOTE_COMMAND
+ },
+ {
+ id: "page-break",
+ title: t("Page break"),
+ description: t("Insert a page break (for printing)"),
+ icon: IconPageBreak,
+ commandName: "pageBreak"
+ },
+ {
+ id: "markdown-import",
+ title: t("Markdown import"),
+ description: t("Import Markdown from the clipboard"),
+ icon: importMarkdownIcon,
+ commandName: MARKDOWN_IMPORT_COMMAND
+ },
+ {
+ id: "anchor",
+ title: t("Anchor"),
+ description: t("Insert an anchor for internal linking"),
+ aliases: [ "bookmark" ],
+ icon: bxBookmark,
+ execute: (target: Editor) => {
+ // Defer to the next event loop tick so the slash command fully finishes its
+ // DOM/selection cleanup; _showFormView needs the view and mapper to be in a settled
+ // state for balloon positioning.
+ setTimeout(() => (target.plugins.get(BookmarkUI) as unknown as { _showFormView(): void })._showFormView(), 0);
+ }
+ }
+ ];
+ }
+
+ // Replaces CKEditor's built-in `bulletedList`/`numberedList`/`todoList` slash commands (removed via
+ // `removeCommands`), whose titles are Title Case, with sentence-case equivalents that run the same
+ // commands.
+ function buildListSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ {
+ id: "bulletedList",
+ title: t("Bulleted list"),
+ description: t("Create a bulleted list"),
+ icon: IconBulletedList,
+ commandName: "bulletedList"
+ },
+ {
+ id: "numberedList",
+ title: t("Numbered list"),
+ description: t("Create a numbered list"),
+ icon: IconNumberedList,
+ commandName: "numberedList"
+ },
+ {
+ id: "todoList",
+ title: t("To-do list"),
+ description: t("Create a to-do list"),
+ icon: IconTodoList,
+ commandName: "todoList"
+ }
+ ];
+ }
+
+ function buildMermaidSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+ const samples = (editor.config.get("mermaid.samples") ?? []) as MermaidSample[];
+
+ // The blank diagram. Replaces CKEditor's built-in `insertMermaidCommand` slash command (removed
+ // via `removeCommands`), which uses a generic icon.
+ const blank: SlashCommandDefinition = {
+ id: "mermaid",
+ title: t("Mermaid diagram"),
+ description: t("Insert an empty Mermaid diagram"),
+ aliases: [ "mermaid", "diagram", "flowchart" ],
+ icon: bxNetworkChart,
+ commandName: INSERT_MERMAID_COMMAND
+ };
+
+ const templates = samples.map((sample, index) => ({
+ id: `mermaid-sample-${index}`,
+ // The sample name is a placeholder rather than an appended string, so a locale can put the
+ // name where its grammar wants it. It arrives already localized, from `mermaid.samples`.
+ title: t("Mermaid diagram: %0", sample.name),
+ description: t("Insert a \"%0\" Mermaid diagram template", sample.name),
+ aliases: [ "mermaid", "diagram", sample.name ],
+ icon: bxNetworkChart,
+ // Inserts a mermaid block pre-filled with the sample source (see insertMermaidCommand).
+ execute: (target: Editor) => target.execute(INSERT_MERMAID_COMMAND, { source: sample.content })
+ }));
+
+ return [ blank, ...templates ];
+ }
+
+ function buildAlignmentSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ {
+ id: "align-left",
+ title: t("Align left"),
+ description: t("Align text to the left"),
+ icon: IconAlignLeft,
+ execute: (target: Editor) => target.execute("alignment", { value: "left" })
+ },
+ {
+ id: "align-center",
+ title: t("Align center"),
+ description: t("Align text to the center"),
+ icon: IconAlignCenter,
+ execute: (target: Editor) => target.execute("alignment", { value: "center" })
+ },
+ {
+ id: "align-right",
+ title: t("Align right"),
+ description: t("Align text to the right"),
+ icon: IconAlignRight,
+ execute: (target: Editor) => target.execute("alignment", { value: "right" })
+ },
+ {
+ id: "align-justify",
+ title: t("Justify"),
+ description: t("Justify text alignment"),
+ icon: IconAlignJustify,
+ execute: (target: Editor) => target.execute("alignment", { value: "justify" })
+ }
+ ];
+ }
+
+ function buildAdmonitionSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+ const icons: Record<AdmonitionType, string> = {
+ note: bxInfoCircle,
+ tip: bxBulb,
+ important: bxCommentError,
+ caution: bxErrorCircle,
+ warning: bxError
+ };
+
+ return ADMONITION_TYPE_NAMES.map((type) => ({
+ id: type,
+ title: getAdmonitionTitle(t, type),
+ description: t("Insert a new admonition"),
+ icon: icons[type],
+ execute: (target: Editor) => target.execute("admonition", { forceValue: type }),
+ aliases: [ "box" ]
+ }));
+ }
+
+ /**
+ * One palette entry per text snippet, restoring premium behaviour: premium `SlashCommand` listed the
+ * premium `Template` plugin's definitions alongside the built-ins. Since `_catalog()` runs on every
+ * query, the definitions are read live from {@link SnippetsEditing} — snippet changes pushed via
+ * `TriliumSnippets.updateDefinitions()` appear in the palette without any re-registration.
+ */
+ function buildSnippetSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ if (!editor.plugins.has(SnippetsEditing)) {
+ return [];
+ }
+
+ return Array.from(editor.plugins.get(SnippetsEditing).definitions, (snippet, index) => ({
+ id: `snippet-${index}`,
+ title: snippet.title,
+ description: snippet.description,
+ // Beyond its own title, every snippet is findable under the feature's generic names.
+ aliases: [ "snippet", "template" ],
+ iconClass: snippet.iconClass,
+ iconColorClass: snippet.iconColorClass,
+ // Gates the entry on `insertTemplate` (read-only mode disables it); `execute` still wins at
+ // commit time, since the command needs the snippet's content as its argument.
+ commandName: "insertTemplate",
+ execute: (target: Editor) => target.execute("insertTemplate", snippet.data)
+ }));
+ }
+
function buildHeadingSlashCommands(editor: Editor): SlashCommandDefinition[] {
const options = (editor.config.get("heading.options") ?? []) as Array<{ model: string; title: string }>;
const icons: Record<string, string> = {