Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(ckeditor): add a GPL AI assistant with streaming preview and replace/insert
Elian Dorana62650caf01f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 63d73e203b..615ef3a426 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -374,6 +374,7 @@"align_right_description": "Align text to the right","justify_description": "Justify text alignment","admonition_description": "Inserts a new admonition",+ "ai_assistant_description": "Ask AI to rewrite the selection or generate new content.","collapsible_description": "Insert a toggleable section that hides/shows content on click.","footnote_description": "Create a new footnote and reference it here","datetime_description": "Insert the current date and time",@@ -2515,6 +2516,15 @@"title_label": "Title","save": "Save"},+ "ai_assistant": {+ "title": "AI assistant",+ "prompt_label": "Ask AI to…",+ "send": "Send",+ "stop": "Stop",+ "replace": "Replace",+ "insert_below": "Insert below",+ "try_again": "Try again"+ },"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",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.tsnew file mode 100644index 0000000000..f195dd95e8--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts@@ -0,0 +1,89 @@+import type { AiStreamFunction } from "@triliumnext/ckeditor5";+import type { LlmChatConfig, LlmMessage, LlmModelInfo } from "@triliumnext/commons";++import { streamChatCompletion } from "../../../services/llm_chat.js";+import options from "../../../services/options.js";++/**+ * Builds the transport behind the editor's AI assistant balloon (`config.aiAssistant.stream`):+ * a completion streamed from the user's default LLM provider through the existing+ * `/api/llm-chat/stream` endpoint, accumulated into the cumulative-HTML shape the plugin expects.+ *+ * Returns `undefined` when no LLM provider is configured, which disables the feature in the+ * editor. Like the snippet list, the provider set is read when the editor is built — configuring+ * a first provider shows the button after the editor is next rebuilt.+ */+export default function buildAiAssistantStream(): AiStreamFunction | undefined {+ if (!readProviderConfigs().length) {+ return undefined;+ }++ return async (request, onData, signal) => {+ const messages: LlmMessage[] = [+ { role: "system", content: SYSTEM_PROMPT },+ {+ role: "user",+ content: request.context+ ? `Content:\n${request.context}\n\nTask: ${request.query}`+ : request.query+ }+ ];++ let cumulative = "";+ await new Promise<void>((resolve, reject) => {+ streamChatCompletion(messages, pickDefaultModel(), {+ onChunk: (text) => {+ cumulative += text;+ onData(cumulative);+ },+ onError: (error) => reject(new Error(error)),+ onDone: () => resolve()+ }, signal).then(+ // A stream that ends without a "done" event (connection dropped) still settles.+ () => resolve(),+ reject+ );+ });+ };+}++/**+ * The assistant works HTML-in/HTML-out: the context is the selection's HTML and the response is+ * committed through the editor's data pipeline, so anything but clean HTML (markdown, fences,+ * commentary) would end up as literal text in the note.+ */+const SYSTEM_PROMPT = `You are a writing assistant embedded in a rich text editor of a note-taking application.+The user gives you a task, usually together with the HTML of the content it applies to.++Rules:+- Respond ONLY with HTML. No markdown, no code fences, no explanations, no preamble.+- Use simple HTML: <p>, <strong>, <em>, <ul>, <ol>, <li>, <h2>-<h5>, <table>, <blockquote>, <code>, <a>.+- When rewriting content, preserve its structure and formatting unless the task says otherwise.+- Respond in the same language as the content, unless the task says otherwise.`;++/** The subset of a stored `llmProviders` entry this module reads. */+interface StoredProviderConfig {+ id: string;+ provider: string;+ selectedModels?: LlmModelInfo[];+}++function readProviderConfigs(): StoredProviderConfig[] {+ return (options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [];+}++/**+ * The provider/model the assistant uses: the first configured provider's default model (or its+ * first model). The same resolution the LLM chat starts out with — a per-run model picker in the+ * balloon can come later.+ */+function pickDefaultModel(): LlmChatConfig {+ for (const config of readProviderConfigs()) {+ const model = config.selectedModels?.find((m) => m.isDefault) ?? config.selectedModels?.[0];+ if (model) {+ return { model: model.id, provider: config.provider, providerId: config.id };+ }+ }+ // No selected models anywhere: let the server resolve the provider's own default.+ return {};+}diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex e011556ddb..7afd0c7960 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -12,6 +12,7 @@ import options from "../../../services/options.js";import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";+import buildAiAssistantStream from "./ai_assistant_stream.js";import { buildToolbarConfig } from "./toolbar.js";export const OPEN_SOURCE_LICENSE_KEY = "GPL";@@ -180,6 +181,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfisnippets: {definitions: opts.templates},+ aiAssistant: {+ // `undefined` when no LLM provider is configured, which disables the feature.+ stream: buildAiAssistantStream()+ },htmlSupport: {allow: JSON.parse(options.get("allowedHtmlTags"))},diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.tsindex 54c0245acb..cb6827eb9c 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts@@ -84,6 +84,7 @@ export function buildClassicToolbar(multilineToolbar: boolean) {"outdent","indent","|",+ "aiAssistant","insertTemplate","markdownImport","cuttonote",@@ -147,6 +148,7 @@ export function buildFloatingToolbar() {"outdent","indent","|",+ "aiAssistant","insertTemplate","markdownImport","specialCharacters",diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.tsindex e90280ea57..6935899586 100644--- a/packages/ckeditor5/src/extra_slash_commands.ts+++ b/packages/ckeditor5/src/extra_slash_commands.ts@@ -22,6 +22,7 @@ import { BookmarkUI } from "ckeditor5";import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";import type { SlashCommandDefinition } from './plugins/mention/slash_commands.js';+import aiIcon from './plugins/ai_assistant/theme/icons/ai.svg?raw';/*** Translation function supplied by the client (which owns i18n). Resolves the@@ -39,6 +40,14 @@ export default function buildExtraCommands(...buildAlignmentExtraCommands(t),...buildAdmonitionExtraCommands(t),...buildMermaidCommands(t, mermaidSamples),+ {+ id: "ai-assistant",+ title: "AI assistant",+ description: t("slash_commands.ai_assistant_description"),+ aliases: [ "ask ai", "assistant" ],+ icon: aiIcon,+ commandName: "aiAssistant"+ },{id: "collapsible",title: "Collapsible block",diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 88514b6226..ebcddb273b 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -13,6 +13,8 @@ export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mentiexport type { TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";+export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";+export type { AiAssistantConfig, AiCompletionRequest, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";export { default as buildExtraCommands } from "./extra_slash_commands.js";export { default as getCkLocale } from "./i18n.js";export * from "./utils.js";diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 2ae2f56fa1..fc00db53bd 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -30,6 +30,7 @@ import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";import CopyLinkUrlButton from "./plugins/copy_link_url.js";import ImageActions from "./plugins/image_actions.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";@@ -90,6 +91,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [CopyLinkUrlButton,ImageActions,TriliumSnippets,+ TriliumAiAssistant,];/**diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.tsnew file mode 100644index 0000000000..c6f92cecbe--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.ts@@ -0,0 +1,42 @@+import { Plugin } from "ckeditor5";++import type { AiAssistantConfig } from "./ai_assistant_config.js";+import AiAssistantEditing, { type ShowAiAssistantCommand } from "./ai_assistant_editing.js";+import AiAssistantUI from "./ai_assistant_ui.js";++/**+ * Trilium's GPL take on the premium `AIAssistant` feature: ask the configured LLM provider to+ * rewrite the selection (or generate new content), watch the response stream into a preview inside+ * the balloon, then commit it with Replace or Insert below — one document write, one undo step.+ *+ * The transport is injected by the host through `config.aiAssistant.stream` (see+ * {@link AiAssistantConfig}), so the plugin works with whatever LLM provider Trilium has+ * configured and stays completely provider-agnostic. Without that callback the feature disables+ * itself.+ */+export default class TriliumAiAssistant extends Plugin {++ static get requires() {+ return [AiAssistantEditing, AiAssistantUI] as const;+ }++ static get pluginName() {+ return "TriliumAiAssistant" as const;+ }+}++declare module "ckeditor5" {+ interface EditorConfig {+ aiAssistant?: AiAssistantConfig;+ }++ interface PluginsMap {+ [TriliumAiAssistant.pluginName]: TriliumAiAssistant;+ [AiAssistantEditing.pluginName]: AiAssistantEditing;+ [AiAssistantUI.pluginName]: AiAssistantUI;+ }++ interface CommandsMap {+ aiAssistant: ShowAiAssistantCommand;+ }+}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsnew file mode 100644index 0000000000..d5c09fd441--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -0,0 +1,43 @@+/**+ * A single completion request made by the AI assistant balloon.+ */+export interface AiCompletionRequest {+ /** The user's instruction — either typed free-form or a preset command's prompt. */+ query: string;++ /**+ * The HTML the instruction applies to (the selection, or on a follow-up query the previous+ * response). Empty when the user generates new content from a collapsed selection.+ */+ context: string;+}++/**+ * Called with the *cumulative* response HTML every time more of the stream arrives — the same+ * contract CKEditor's premium `AITextAdapter` uses. Re-parsing the growing prefix keeps the+ * preview renderable at every tick (the HTML parser auto-closes tags cut off mid-stream).+ */+export type AiStreamCallback = (cumulativeHtml: string) => void;++/**+ * Host-provided transport for AI completions. The plugin knows nothing about providers, endpoints+ * or authentication — the client injects this the same way it injects `snippets.definitions` or+ * `syntaxHighlighting.loadHighlightJs`.+ *+ * The returned promise resolves when the stream finishes and rejects on transport or provider+ * error. An abort through `signal` must reject with a DOM `AbortError`; the partial content+ * already delivered through `onData` stays usable.+ */+export type AiStreamFunction = (+ request: AiCompletionRequest,+ onData: AiStreamCallback,+ signal: AbortSignal+) => Promise<void>;++export interface AiAssistantConfig {+ /**+ * Streams a completion for a request. When absent (no LLM provider configured), the whole+ * feature stays disabled.+ */+ stream?: AiStreamFunction;+}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.tsnew file mode 100644index 0000000000..e21d0dd4be--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.ts@@ -0,0 +1,55 @@+import { Command, Plugin } from "ckeditor5";++import type { AiAssistantConfig } from "./ai_assistant_config.js";+import type AiAssistantUI from "./ai_assistant_ui.js";++/**+ * The model marker pinning the text the assistant was opened on. Unlike the live selection it+ * survives focus moving into the balloon, and it is remapped as the user keeps editing, so+ * "Replace" always hits the content that was originally selected. `affectsData: false` keeps it+ * out of the document data and the undo stack.+ */+export const AI_TARGET_MARKER = "triliumAiTarget";++/**+ * The editing side of the AI assistant: the target-marker highlight and the `aiAssistant` command.+ * There is no schema or data conversion — the feature never stores anything in the document until+ * the user commits, and then it inserts perfectly ordinary content.+ */+export default class AiAssistantEditing extends Plugin {++ static get pluginName() {+ return "AiAssistantEditing" as const;+ }++ public init(): void {+ const editor = this.editor;++ // Editing-only: the tint shows what "Replace" will hit; the data never contains the marker.+ editor.conversion.for("editingDowncast").markerToHighlight({+ model: AI_TARGET_MARKER,+ view: { classes: "ck-ai-assistant-target" }+ });++ editor.commands.add("aiAssistant", new ShowAiAssistantCommand(editor));+ }+}++/**+ * Opens the AI assistant balloon on the current selection. Exists as a command (rather than the+ * button calling the UI directly) so keystrokes and slash-command entries can gate on and trigger+ * the feature the same way they do every other one.+ */+export class ShowAiAssistantCommand extends Command {++ public override refresh(): void {+ const config = this.editor.config.get("aiAssistant") as AiAssistantConfig | undefined;+ this.isEnabled = !!config?.stream;+ }++ public override execute(): void {+ // Looked up by name: the command lives in the editing plugin, and a class import of the UI+ // plugin here would cycle (UI → editing → UI). The type still resolves via `PluginsMap`.+ (this.editor.plugins.get("AiAssistantUI") as AiAssistantUI).show();+ }+}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.tsnew file mode 100644index 0000000000..0784657514--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts@@ -0,0 +1,279 @@+import {+ ButtonView,+ createLabeledInputText,+ FocusCycler,+ FocusTracker,+ KeystrokeHandler,+ LabeledFieldView,+ submitHandler,+ View,+ ViewCollection,+ type FocusableView,+ type InputTextView,+ type Locale+} from "ckeditor5";++/** 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";++/**+ * The AI assistant balloon: a prompt row, a read-only streaming preview styled like note content,+ * and the review actions. Purely presentational — the orchestration (markers, streaming, committing+ * to the model) lives in `AiAssistantUI`, which listens to this view's `submit`, `stop`, `replace`,+ * `insertBelow` and `tryAgain` events.+ */+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;++ public readonly promptInputView: LabeledFieldView<InputTextView>;+ public readonly sendButtonView: 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) {+ super(locale);++ this.set("phase", "prompt");+ this.set("query", "");+ this.set("errorMessage", "");++ this.promptInputView = this._createPromptInput(locale, translate);+ this.sendButtonView = this._createSendButton(locale, translate);+ 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.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");++ 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: [{ text: translate("ai_assistant.title", "AI assistant") }]+ },+ 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.promptInputView, this.sendButtonView]+ },+ {+ tag: "div",+ attributes: { class: ["ck", "ck-ai-assistant-form__actions"] },+ children: [+ this.stopButtonView,+ this.replaceButtonView,+ this.insertBelowButtonView,+ this.tryAgainButtonView+ ]+ }+ ]+ });++ 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.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.previewView.setContent("");+ }++ /** Enters the streaming phase with an empty preview. */+ public beginStreaming(): void {+ this.phase = "streaming";+ this.errorMessage = "";+ this.previewView.setContent("");+ }++ /** Renders the (sanitized, cumulative) response received so far. */+ public setPreview(html: string): void {+ this.previewView.setContent(html);+ }++ /**+ * Leaves the streaming phase. With content the form enters review; a run that produced+ * nothing falls back to the prompt phase, showing `errorMessage` when the run failed.+ */+ public endStreaming(hasContent: boolean, errorMessage: string): void {+ this.phase = hasContent ? "review" : "prompt";+ this.errorMessage = errorMessage;+ }++ public focus(): void {+ this._focusCycler.focusFirst();+ }++ private _createPromptInput(locale: Locale, translate: Translate) {+ const input = new LabeledFieldView(locale, createLabeledInputText);+ input.label = translate("ai_assistant.prompt_label", "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) {+ const button = new ButtonView(locale);+ button.set({+ label: translate("ai_assistant.send", "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",+ 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 --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsnew file mode 100644index 0000000000..574fb8d688--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -0,0 +1,313 @@+import {+ ButtonView,+ clickOutsideHandler,+ ContextualBalloon,+ Plugin,+ type ModelNode,+ type ModelRange+} from "ckeditor5";++import { translate } from "../translate.js";+import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";+import AiAssistantFormView 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 command = editor.commands.get("aiAssistant");+ const buttonView = new ButtonView(locale);++ buttonView.set({+ label: translate(editor, "ai_assistant.title", "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 = "";++ 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));+ this._formView = form;++ form.on("submit", () => {+ const query = form.query.trim();+ if (query) {+ form.query = "";+ void this._run(query);+ }+ });+ 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);+ });++ // 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 = "";+ try {+ await stream({ query, context: this._context }, onData, abortController.signal);+ } 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;+ }+ form.endStreaming(!!this._cumulative, errorMessage);+ }++ /**+ * 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 --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.tsnew file mode 100644index 0000000000..c1c8fbf2c5--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";++import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";++describe("sanitizeAiHtml", () => {+ it("keeps ordinary formatting untouched", () => {+ const html = "<p>Hello <strong>world</strong></p><ul><li>one</li></ul>";+ expect(sanitizeAiHtml(html)).toBe(html);+ });++ it("removes active content: script-like elements, event handlers and javascript: URLs", () => {+ expect(sanitizeAiHtml("<p>ok</p><script>alert(1)</script><style>p{}</style><iframe src='x'></iframe>"))+ .toBe("<p>ok</p>");+ expect(sanitizeAiHtml("<p onclick=\"alert(1)\" class=\"keep\">ok</p>"))+ .toBe("<p class=\"keep\">ok</p>");+ expect(sanitizeAiHtml("<a href=\"javascript:alert(1)\">x</a><a href=\"https://example.com\">y</a>"))+ .toBe("<a>x</a><a href=\"https://example.com\">y</a>");+ });++ it("keeps a renderable result for HTML cut off mid-stream", () => {+ expect(sanitizeAiHtml("<p>This is an exam")).toBe("<p>This is an exam</p>");+ });+});++describe("stripMarkdownFences", () => {+ it("returns unfenced content unchanged", () => {+ expect(stripMarkdownFences("<p>plain</p>")).toBe("<p>plain</p>");+ });++ it("strips a complete ```html fence pair", () => {+ expect(stripMarkdownFences("```html\n<p>hi</p>\n```")).toBe("<p>hi</p>\n");+ expect(stripMarkdownFences("```\n<p>hi</p>\n```\n")).toBe("<p>hi</p>\n");+ });++ it("strips an opening fence whose closing half has not streamed in yet", () => {+ expect(stripMarkdownFences("```html\n<p>st")).toBe("<p>st");+ });++ it("does not treat a ``` inside the content as a closing fence", () => {+ expect(stripMarkdownFences("```html\n<p>use ``` for fences</p>\n<p>more</p>"))+ .toBe("<p>use ``` for fences</p>\n<p>more</p>");+ });+});diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.tsnew file mode 100644index 0000000000..dfd753da41--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts@@ -0,0 +1,55 @@+/**+ * Pure HTML helpers for the AI assistant: making a streamed model response safe to show in the+ * preview element, and undoing the models' habit of wrapping HTML output in markdown fences.+ *+ * The commit path (Replace / Insert below) does not rely on this — it goes through the editor's+ * data pipeline, where the schema drops anything the editor cannot represent. Sanitizing here+ * only protects the raw `innerHTML` preview.+ */++const DISALLOWED_ELEMENTS = ["script", "style", "iframe", "object", "embed", "link", "meta", "form"];++/**+ * Strips active content from an HTML string so it can be assigned to the preview's `innerHTML`:+ * script-like elements, `on*` event attributes, and `javascript:` URLs.+ */+export function sanitizeAiHtml(html: string): string {+ const doc = new DOMParser().parseFromString(html, "text/html");++ for (const element of doc.querySelectorAll(DISALLOWED_ELEMENTS.join(","))) {+ element.remove();+ }++ for (const element of doc.body.querySelectorAll("*")) {+ for (const attribute of Array.from(element.attributes)) {+ const name = attribute.name.toLowerCase();+ const isEventHandler = name.startsWith("on");+ const isScriptUrl = (name === "href" || name === "src")+ && attribute.value.trim().toLowerCase().startsWith("javascript:");+ if (isEventHandler || isScriptUrl) {+ element.removeAttribute(attribute.name);+ }+ }+ }++ return doc.body.innerHTML;+}++/**+ * Removes a leading markdown code fence (```html or ```) and, when present, the matching closing+ * fence. Models add these despite instructions not to; the stripper is applied to the cumulative+ * stream, so it must also handle a fence whose closing half has not arrived yet.+ */+export function stripMarkdownFences(cumulative: string): string {+ const opening = /^\s*```[a-z]*\s*\n?/i.exec(cumulative);+ if (!opening) {+ return cumulative;+ }++ let body = cumulative.slice(opening[0].length);+ const closingIndex = body.lastIndexOf("```");+ if (closingIndex !== -1 && body.slice(closingIndex + 3).trim() === "") {+ body = body.slice(0, closingIndex);+ }+ return body;+}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.cssnew file mode 100644index 0000000000..a024eebffe--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css@@ -0,0 +1,54 @@+.ck.ck-ai-assistant-form {+ display: flex;+ flex-direction: column;+ gap: var(--ck-spacing-medium);+ padding: var(--ck-spacing-large);+ width: min(560px, 90vw);+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__heading {+ font-weight: bold;+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row {+ display: flex;+ align-items: flex-end;+ gap: var(--ck-spacing-small);+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row .ck-labeled-field-view {+ flex-grow: 1;+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview {+ max-height: 320px;+ overflow-y: auto;+ border: 1px solid var(--ck-color-base-border);+ border-radius: var(--ck-border-radius);+ padding: var(--ck-spacing-medium);+ background: var(--ck-color-base-background);+}++/* 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 {+ display: none;+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__error {+ color: var(--ck-color-base-error);+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__actions {+ display: flex;+ gap: var(--ck-spacing-small);+}++/* An actions row with every button hidden should not reserve a gap's worth of height. */+.ck.ck-ai-assistant-form .ck-ai-assistant-form__actions:not(:has(.ck-button:not(.ck-hidden))) {+ display: none;+}++/* The tint on the note text the assistant was opened on — what "Replace" will hit. */+.ck-content .ck-ai-assistant-target {+ background: rgba(148, 112, 219, 0.22);+}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/icons/ai.svg b/packages/ckeditor5/src/plugins/ai_assistant/theme/icons/ai.svgnew file mode 100644index 0000000000..7608c42f70--- /dev/null+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/icons/ai.svg@@ -0,0 +1 @@+<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M11.7 1.7a.4.4 0 0 1 .76 0l1.07 3.07a.4.4 0 0 0 .25.25l3.07 1.07a.4.4 0 0 1 0 .75l-3.07 1.08a.4.4 0 0 0-.25.24l-1.07 3.08a.4.4 0 0 1-.75 0L10.63 8.16a.4.4 0 0 0-.24-.24L7.31 6.84a.4.4 0 0 1 0-.75l3.08-1.07a.4.4 0 0 0 .24-.25l1.08-3.07ZM4.6 9.9a.35.35 0 0 1 .66 0l.77 2.2a.35.35 0 0 0 .21.22l2.2.77a.35.35 0 0 1 0 .66l-2.2.77a.35.35 0 0 0-.21.21l-.77 2.2a.35.35 0 0 1-.66 0l-.77-2.2a.35.35 0 0 0-.22-.21l-2.2-.77a.35.35 0 0 1 0-.66l2.2-.77a.35.35 0 0 0 .22-.21l.77-2.2Zm9.55 4.02a.3.3 0 0 1 .56 0l.5 1.42a.3.3 0 0 0 .18.18l1.42.5a.3.3 0 0 1 0 .56l-1.42.5a.3.3 0 0 0-.18.18l-.5 1.42a.3.3 0 0 1-.56 0l-.5-1.42a.3.3 0 0 0-.18-.18l-1.42-.5a.3.3 0 0 1 0-.56l1.42-.5a.3.3 0 0 0 .18-.18l.5-1.42Z"/></svg>