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
refactor(ai-assistant): move the assistant from a balloon into a non-modal dialog
Elian Doran8ed0f9270445
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.tsindex c6f92cecbe..f60ad828f0 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant.ts@@ -7,7 +7,7 @@ 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 dialog, 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 hasdiff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 3d5d898a31..b64acef13b 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -1,5 +1,5 @@/**- * A single completion request made by the AI assistant balloon.+ * A single completion request made by the AI assistant.*/export interface AiCompletionRequest {/** The user's instruction — either typed free-form or a preset command's prompt. */@@ -74,7 +74,7 @@ export interface AiQuickAction {}/**- * Sanitizes model-produced HTML before the balloon assigns it to the preview's `innerHTML`.+ * Sanitizes model-produced HTML before the dialog assigns it to the preview's `innerHTML`.** CKEditor ships no sanitizer of its own and asks the integrator for one instead — the same* contract as `config.htmlEmbed.sanitizeHtml`, whose built-in default only warns and passes thediff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.tsindex e21d0dd4be..7b6b574cc7 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_editing.ts@@ -5,7 +5,7 @@ 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+ * survives focus moving into the dialog, 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.*/@@ -36,7 +36,7 @@ export default class AiAssistantEditing extends Plugin {}/**- * Opens the AI assistant balloon on the current selection. Exists as a command (rather than the+ * Opens the AI assistant dialog 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.*/diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.tsindex acbea010e7..fbfe0901d5 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@@ -25,7 +25,7 @@ describe("AiAssistantFormView", () => {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.+ // Without the reset exemption, the body wrapper's `.ck-reset_all` nowraps every paragraph.expect(form.previewView.element?.classList.contains("ck-reset_all-excluded")).toBe(true);});diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.tsindex 668e8a735b..3db389cbf4 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts@@ -24,8 +24,8 @@ export type AiAssistantFormPhase = "prompt" | "streaming" | "review";export type AiAssistantViewMode = "result" | "changes";/**- * The AI assistant balloon: a prompt row, a read-only streaming preview styled like note content,- * and the review actions. In the review phase the preview can toggle between the plain result and+ * The AI assistant dialog's contents: 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.@@ -103,17 +103,11 @@ export default class AiAssistantFormView extends View {},children: [{+ // The feature's title belongs to the dialog's own header; all this row carries+ // is the Result/Changes toggle, and only when a review has a diff to offer.tag: "div",- attributes: { class: ["ck", "ck-ai-assistant-form__heading"] },- children: [- {- tag: "span",- attributes: { class: ["ck", "ck-ai-assistant-form__title"] },- children: [{ text: t("AI assistant") }]- },- this.resultToggleView,- this.changesToggleView- ]+ attributes: { class: ["ck", "ck-ai-assistant-form__viewmodes"] },+ children: [this.resultToggleView, this.changesToggleView]},this.previewView,{@@ -339,9 +333,10 @@ class AiPreviewView extends View {"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+ // Exempt the preview subtree from CKEditor's UI reset. Balloons and dialogs+ // alike are mounted into `editor.ui.view.body`, whose wrapper carries+ // `.ck-reset_all` — which 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)diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.tsindex a23ba25f98..5fc725da02 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts@@ -1,4 +1,4 @@-import { _setModelData as setModelData, ButtonView, ClassicEditor, ContextualBalloon, Essentials, Paragraph, SplitButtonView } from "ckeditor5";+import { _setModelData as setModelData, ButtonView, ClassicEditor, Dialog, Essentials, Paragraph, SplitButtonView } from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";@@ -92,6 +92,14 @@ function quickActionButtons(dropdown: QuickActionsDropdown): ListButtonView[] {return quickActionGroups(dropdown).flatMap((group) => group.buttons);}+/** The form the assistant put into the dialog, once it is open. */+function openForm(editor: ClassicEditor) {+ return editor.plugins.get(Dialog).view?.contentView?.children.get(0) as unknown as {+ query: string;+ fire(event: string): void;+ };+}+describe("AiAssistantUI toolbar entry", () => {it("is a plain button when the host configured no quick actions", async () => {const editor = await createEditor(undefined, createStreamStub().stream);@@ -142,18 +150,45 @@ describe("AiAssistantUI toolbar entry", () => {]);});- it("gates the content-requiring actions on the selection", () => {+ it("gates the content-requiring actions on there being something to work on", () => {const [fixTypos, , write] = quickActionButtons(dropdown);- setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ setModelData(editor.model, "<paragraph>[]</paragraph>");expect(fixTypos.isEnabled).toBe(false);expect(write.isEnabled).toBe(true);+ // A collapsed caret is enough as long as its block has content: that is what the run+ // falls back to.+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ expect(fixTypos.isEnabled).toBe(true);+setModelData(editor.model, "<paragraph>[foo]</paragraph>");expect(fixTypos.isEnabled).toBe(true);});- it("runs the picked action against the selection and opens the balloon on it", async () => {+ it("falls back to the caret's block when nothing is selected", async () => {+ setModelData(editor.model, "<paragraph>first</paragraph><paragraph>seco[]nd</paragraph>");+ const [fixTypos] = quickActionButtons(dropdown);++ fixTypos.fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(1));++ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "second" });+ });++ it("keeps a free-form prompt at a collapsed caret generating from scratch", async () => {+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");+ editor.execute("aiAssistant");++ const form = openForm(editor);+ form.query = "Write a haiku.";+ form.fire("submit");+ await vi.waitFor(() => expect(requests).toHaveLength(1));++ expect(requests[0]).toEqual({ query: "Write a haiku.", context: "" });+ });++ it("runs the picked action against the selection and opens the dialog on it", async () => {setModelData(editor.model, "<paragraph>[foo]</paragraph>");const [fixTypos] = quickActionButtons(dropdown);@@ -162,8 +197,9 @@ describe("AiAssistantUI toolbar entry", () => {expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "foo" });- const balloon = editor.plugins.get(ContextualBalloon);- expect(balloon.visibleView).not.toBeNull();+ const dialog = editor.plugins.get(Dialog);+ expect(dialog.isOpen).toBe(true);+ expect(dialog.id).toBe("aiAssistant");});it("closes itself off while a run is in flight", async () => {diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex dda199c116..fc03536346 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -2,10 +2,10 @@ import {addListToDropdown,ButtonView,CKEditorError,- clickOutsideHandler,Collection,- ContextualBalloon,createDropdown,+ Dialog,+ DialogViewPosition,Plugin,SplitButtonView,ViewModel,@@ -30,18 +30,28 @@ import "./theme/ai_assistant.css";*/const RENDER_THROTTLE_MS = 80;+/** Identifies our dialog in the editor-wide `Dialog` plugin, which shows one dialog at a time. */+const DIALOG_ID = "aiAssistant";+/*** The AI assistant's UI and orchestration: the toolbar entry (a split button whose menu holds the- * host's quick actions), the balloon form, and the stream-preview-commit lifecycle.+ * host's quick actions), the dialog 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.+ *+ * The form lives in a **non-modal dialog** rather than a balloon. A balloon anchors to the target+ * text, which means it has to be repositioned on every streamed chunk and still ends up covering+ * the very content being rewritten on a large selection; it also shares one stack with the balloon+ * toolbar that `PopupEditor` (floating-toolbar mode) shows on exactly the selections the assistant+ * opens on. The dialog is anchored to the editor instead, is draggable, and leaves the document+ * visible and editable — so the target highlight stays on screen while the response is reviewed.*/export default class AiAssistantUI extends Plugin {static get requires() {- return [AiAssistantEditing, ContextualBalloon] as const;+ return [AiAssistantEditing, Dialog] as const;}static get pluginName() {@@ -79,7 +89,7 @@ export default class AiAssistantUI extends Plugin {editor.ui.componentFactory.add("aiAssistant", (locale) => this._createToolbarComponent(locale));- // While the balloon is closed the quick actions are offered against the selection, so+ // While the assistant is closed the quick actions are offered against the selection, so// their enablement has to follow it.this.listenTo(editor.model.document.selection, "change:range", () => this._updateHasContext());}@@ -166,8 +176,7 @@ export default class AiAssistantUI extends Plugin {// and its arrow to the dropdown's `open`.dropdownView.on("execute", (evt) => {const { _quickAction } = evt.source as unknown as { _quickAction: AiQuickAction };- this.show();- void this._run(_quickAction.prompt);+ this.runQuickAction(_quickAction);});return dropdownView;@@ -179,29 +188,47 @@ export default class AiAssistantUI extends Plugin {this._formView?.destroy();}- /** Opens the balloon on the current selection. Invoked by the `aiAssistant` command. */+ /** Opens the assistant on the current selection. Invoked by the `aiAssistant` command. */public show(): void {+ this._open(false);+ }++ /**+ * Opens the assistant and runs a preset instruction against the caret's surroundings. Both+ * entry points to the quick actions — the toolbar menu and the `/` palette — come in this way.+ */+ public runQuickAction(action: AiQuickAction): void {+ this._open(true);+ void this._run(action.prompt);+ }++ /**+ * @param fallbackToBlock widens a collapsed caret to the block it sits in. A quick action is an+ * instruction *about* content ("Fix typos"), so it needs something to+ * work on, while a free-form prompt typed at a collapsed caret+ * legitimately means "generate here" and must keep an empty context.+ */+ private _open(fallbackToBlock: boolean): void {const editor = this.editor;- const balloon = editor.plugins.get(ContextualBalloon);+ const dialog = editor.plugins.get(Dialog);const form = this._getForm();- if (balloon.hasView(form)) {+ if (dialog.id === DIALOG_ID) {form.focus();return;}- // Capture the context and pin the target before focus moves into the balloon and the+ // Capture the context and pin the target before focus moves into the dialog and the// document selection stops being trustworthy.const model = editor.model;- const selection = model.document.selection;- this._context = selection.isCollapsed+ const range = this._resolveTargetRange(fallbackToBlock);+ this._context = !range || range.isCollapsed? ""- : editor.data.stringify(model.getSelectedContent(selection));+ : editor.data.stringify(model.getSelectedContent(model.createSelection(range)));this._previousContext = this._context;this._cumulative = "";this._updateHasContext();- const range = selection.getFirstRange();/* v8 ignore next -- the document selection always has at least one range */if (range) {model.change((writer) => {@@ -210,7 +237,19 @@ export default class AiAssistantUI extends Plugin {}form.reset();- balloon.add({ view: form, position: this._getBalloonPosition() });+ dialog.show({+ id: DIALOG_ID,+ // A header is what makes the dialog draggable, so the user can move it off the text+ // being rewritten.+ title: editor.t("AI assistant"),+ icon: aiIcon,+ isModal: false,+ position: DialogViewPosition.EDITOR_CENTER,+ content: form,+ // Covers every way out — Esc, the close button, another dialog taking over — not just+ // the paths that go through `_hide()`.+ onHide: () => this._reset()+ });form.focus();}@@ -239,31 +278,9 @@ export default class AiAssistantUI extends Plugin {void this._run(this._lastQuery);});- // The Result and Changes views usually differ in height; keep the balloon anchored.- this.listenTo(form, "change:viewMode", () => {- const balloon = this.editor.plugins.get(ContextualBalloon);- if (balloon.visibleView === form) {- balloon.updatePosition();- }- });-- // Esc always dismisses. A click outside only dismisses an idle, empty form — mid-stream or- // with a response on screen it would silently throw the result away.- form.keystrokes.set("Esc", (_data, cancel) => {- 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();- }- }- });-+ // Esc and the close button are the dialog's own; it also stays put as the preview grows+ // and when the Result/Changes toggle changes its height, so there is nothing to reposition+ // and no click-outside dismissal that could throw a streamed response away.return form;}@@ -285,14 +302,7 @@ export default class AiAssistantUI extends Plugin {const abortController = new AbortController();this._abortController = abortController;- const balloon = editor.plugins.get(ContextualBalloon);- const render = (html: string) => {- form.setPreview(this._sanitize(html));- // The preview grows as it fills; keep the balloon anchored rather than overflowing.- if (balloon.visibleView === form) {- balloon.updatePosition();- }- };+ const render = (html: string) => form.setPreview(this._sanitize(html));let renderTimer: ReturnType<typeof setTimeout> | null = null;let pendingHtml: string | null = null;@@ -449,10 +459,23 @@ export default class AiAssistantUI extends Plugin {return marker?.getRange() ?? model.document.selection.getFirstRange() ?? null;}+ /** Closes the assistant. The teardown itself rides on the dialog's `onHide`. */private _hide(): void {+ const dialog = this.editor.plugins.get(Dialog);+ // Only our own: `hide()` closes whatever dialog is open, and another feature's must not be+ // collateral damage.+ if (dialog.id === DIALOG_ID) {+ dialog.hide();+ }+ }++ /**+ * Returns the plugin to its closed state. Invoked from the dialog's `onHide`, so it runs+ * however the assistant was dismissed. The dialog handles removing the form and restoring+ * focus to the editing view.+ */+ private _reset(): void {const editor = this.editor;- const balloon = editor.plugins.get(ContextualBalloon);- const form = this._formView;this._abortController?.abort();this._cumulative = "";@@ -465,34 +488,35 @@ export default class AiAssistantUI extends Plugin {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();+ this._formView?.reset();}/*** What the quick actions are offered against: whatever the assistant captured while open, or- * the selection once it is closed.+ * once it is closed, whatever a run started now would work on.*/private _updateHasContext(): void {- this.hasContext = !!this._context || !this.editor.model.document.selection.isCollapsed;+ const range = this._resolveTargetRange(true);+ this.hasContext = !!this._context || (!!range && !range.isCollapsed);}- 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;- }- };+ /**+ * The range a run works on: the selection, or — for a quick action at a collapsed caret — the+ * block it sits in, so "Fix typos" typed into a paragraph rewrites that paragraph. It is both+ * the context handed to the model and what the target marker pins for "Replace".+ */+ private _resolveTargetRange(fallbackToBlock: boolean): ModelRange | null {+ const model = this.editor.model;+ const selection = model.document.selection;+ const range = selection.getFirstRange();++ if (!fallbackToBlock || !selection.isCollapsed) {+ return range;+ }++ const block = selection.getFirstPosition()?.parent;+ /* v8 ignore next -- a collapsed selection always sits inside an element */+ return block?.is("element") ? model.createRangeIn(block) : range;}}diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.cssindex b169ee8d66..6aa8ace880 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css@@ -6,19 +6,15 @@width: min(560px, 90vw);}-.ck.ck-ai-assistant-form .ck-ai-assistant-form__heading {+.ck.ck-ai-assistant-form .ck-ai-assistant-form__viewmodes {display: flex;align-items: center;gap: var(--ck-spacing-small);- font-weight: bold;}-.ck.ck-ai-assistant-form .ck-ai-assistant-form__title {- flex-grow: 1;-}--.ck.ck-ai-assistant-form .ck-button.ck-ai-assistant-form__viewmode {- font-weight: normal;+/* Outside a review with a diff both toggles are hidden; an empty row should not reserve a gap. */+.ck.ck-ai-assistant-form .ck-ai-assistant-form__viewmodes:not(:has(.ck-button:not(.ck-hidden))) {+ display: none;}.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row {