Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): move the AI quick actions to the toolbar entry

Elian Dorana7f5db8da9c2
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index cf09de29e9..13ce462d19 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3923,7 +3923,6 @@
"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",
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index 5f3ce93daa..3d5d898a31 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -56,19 +56,19 @@ export type AiStreamFunction = (
export type AiDiffFunction = (oldHtml: string, newHtml: string) => string;
/**
- * A predefined instruction offered in the balloon's "Quick actions" dropdown — the GPL counterpart
- * of the premium `AICommandDefinition`. Labels arrive pre-translated from the host; only the
- * `prompt` is sent to the model.
+ * A predefined instruction offered in the menu of the toolbar's AI entry — the GPL counterpart of
+ * the premium `AICommandDefinition`. Labels arrive pre-translated from the host; only the `prompt`
+ * is sent to the model.
*/
export interface AiQuickAction {
id: string;
- /** The label shown in the dropdown, already translated by the host. */
+ /** The label shown in the menu, already translated by the host. */
label: string;
/** The instruction sent to the model in place of a typed query. */
prompt: string;
/**
* Whether the action needs content to work on. Actions that do (the default) are disabled
- * when the assistant was opened on an empty selection and nothing has been generated yet.
+ * while there is nothing selected and nothing has been generated yet.
*/
requiresContent?: boolean;
}
@@ -83,7 +83,7 @@ export interface AiQuickAction {
*/
export type AiSanitizeFunction = (html: string) => string;
-/** A labelled group of quick actions, rendered as a group in the dropdown. */
+/** A labelled group of quick actions, rendered as a group in the menu. */
export interface AiQuickActionGroup {
id: string;
/** The group heading, already translated by the host. */
@@ -107,9 +107,9 @@ export interface AiAssistantConfig {
diff?: AiDiffFunction;
/**
- * The predefined instructions offered in the balloon's "Quick actions" dropdown ("Fix typos",
- * "Make shorter", …). Optional — without them the dropdown is hidden and only the free-form
- * prompt remains.
+ * The predefined instructions hanging off the toolbar entry ("Fix typos", "Make shorter", …).
+ * Optional — without them the toolbar entry is a plain button and only the free-form prompt
+ * remains.
*/
quickActions?: AiQuickActionGroup[];
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
index c60e6f5247..acbea010e7 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,34 +1,16 @@
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(), quickActions);
+function makeForm(): AiAssistantFormView {
+ form = new AiAssistantFormView(new Locale());
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 ?? "";
}
@@ -120,37 +102,6 @@ describe("AiAssistantFormView", () => {
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();
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
index ac1839598f..668e8a735b 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -1,8 +1,5 @@
import {
- addListToDropdown,
ButtonView,
- Collection,
- createDropdown,
createLabeledInputText,
FocusCycler,
FocusTracker,
@@ -11,17 +8,11 @@ import {
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";
-
/**
* 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
@@ -32,12 +23,6 @@ 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
@@ -58,11 +43,6 @@ export default class AiAssistantFormView extends View {
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 = "";
@@ -71,7 +51,6 @@ export default class AiAssistantFormView extends View {
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;
@@ -86,7 +65,7 @@ export default class AiAssistantFormView extends View {
private readonly _focusables = new ViewCollection<FocusableView>();
private readonly _focusCycler: FocusCycler;
- constructor(locale: Locale, quickActions: AiQuickActionGroup[] = []) {
+ constructor(locale: Locale) {
super(locale);
const t = locale.t;
@@ -97,14 +76,12 @@ export default class AiAssistantFormView extends View {
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, 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);
@@ -153,7 +130,7 @@ export default class AiAssistantFormView extends View {
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },
- children: [this.quickActionsDropdownView, this.promptInputView, this.sendButtonView]
+ children: [this.promptInputView, this.sendButtonView]
},
{
tag: "div",
@@ -199,7 +176,6 @@ export default class AiAssistantFormView extends View {
const focusables = [
this.resultToggleView,
this.changesToggleView,
- this.quickActionsDropdownView,
this.promptInputView,
this.sendButtonView,
this.stopButtonView,
@@ -282,53 +258,6 @@ export default class AiAssistantFormView extends View {
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, groups: AiQuickActionGroup[]) {
- const dropdown = createDropdown(locale);
-
- dropdown.buttonView.set({
- 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);
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
new file mode 100644
index 0000000000..a23ba25f98
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
@@ -0,0 +1,198 @@
+import { _setModelData as setModelData, ButtonView, ClassicEditor, ContextualBalloon, Essentials, Paragraph, SplitButtonView } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import TriliumAiAssistant from "./ai_assistant.js";
+import type { AiCompletionRequest, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./ai_assistant_config.js";
+import AiAssistantUI from "./ai_assistant_ui.js";
+
+// ---- Typed views of the dropdown internals ----
+
+interface ListButtonView {
+ label?: string;
+ isEnabled: boolean;
+ fire(event: string): void;
+}
+
+interface ListItemView {
+ children: { get(idx: number): ListButtonView };
+}
+
+interface ListGroupView {
+ label: string;
+ items: { get(idx: number): ListItemView };
+}
+
+interface QuickActionsDropdown {
+ isOpen: boolean;
+ isEnabled: boolean;
+ class?: string;
+ buttonView: SplitButtonView;
+ panelView: { children: { get(idx: number): { items: { get(idx: number): ListGroupView } } } };
+}
+
+const QUICK_ACTIONS: AiQuickActionGroup[] = [
+ {
+ id: "edit",
+ label: "Edit or review",
+ actions: [
+ { id: "fixTypos", label: "Fix typos", prompt: "Fix all mistakes." },
+ { id: "makeShorter", label: "Make shorter", prompt: "Shorten it." }
+ ]
+ },
+ {
+ id: "generate",
+ label: "Generate",
+ actions: [
+ { id: "write", label: "Write something", prompt: "Write a paragraph.", requiresContent: false }
+ ]
+ }
+];
+
+/**
+ * The plugin requires a host sanitizer and refuses to render without one; the tests assert on the
+ * HTML they feed in, so the double passes it through untouched.
+ */
+const sanitizeHtml = (html: string) => html;
+
+/** The requests handed to the stream, in order, plus the stub itself. */
+function createStreamStub(response = "<p>done</p>") {
+ const requests: AiCompletionRequest[] = [];
+ const stream: AiStreamFunction = async (request: AiCompletionRequest, onData: AiStreamCallback) => {
+ requests.push(request);
+ onData(response);
+ };
+ return { requests, stream };
+}
+
+async function createEditor(quickActions?: AiQuickActionGroup[], stream?: AiStreamFunction) {
+ return createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {
+ aiAssistant: { stream, quickActions, sanitizeHtml }
+ });
+}
+
+function createComponent(editor: ClassicEditor) {
+ return editor.ui.componentFactory.create("aiAssistant") as unknown as QuickActionsDropdown;
+}
+
+/** Opens the dropdown — `addListToDropdown` only populates the panel on the first open. */
+function quickActionGroups(dropdown: QuickActionsDropdown): Array<{ label: string; buttons: ListButtonView[] }> {
+ dropdown.isOpen = true;
+
+ const list = dropdown.panelView.children.get(0);
+ return QUICK_ACTIONS.map((configured, groupIdx) => {
+ const group = list.items.get(groupIdx);
+ const buttons = configured.actions.map((_action, itemIdx) => group.items.get(itemIdx).children.get(0));
+ return { label: group.label, buttons };
+ });
+}
+
+/** The action buttons of every group, flattened into definition order. */
+function quickActionButtons(dropdown: QuickActionsDropdown): ListButtonView[] {
+ return quickActionGroups(dropdown).flatMap((group) => group.buttons);
+}
+
+describe("AiAssistantUI toolbar entry", () => {
+ it("is a plain button when the host configured no quick actions", async () => {
+ const editor = await createEditor(undefined, createStreamStub().stream);
+ const button = editor.ui.componentFactory.create("aiAssistant") as ButtonView;
+ const showSpy = vi.spyOn(editor.plugins.get(AiAssistantUI), "show");
+
+ expect(button).toBeInstanceOf(ButtonView);
+ expect(button.label).toBe("AI assistant");
+ expect(button.icon).toContain("<svg");
+ expect(button.isEnabled).toBe(true);
+
+ button.fire("execute");
+ expect(showSpy).toHaveBeenCalled();
+ });
+
+ describe("with quick actions configured", () => {
+ let editor: ClassicEditor;
+ let dropdown: QuickActionsDropdown;
+ let requests: AiCompletionRequest[];
+
+ beforeEach(async () => {
+ const stub = createStreamStub();
+ requests = stub.requests;
+ editor = await createEditor(QUICK_ACTIONS, stub.stream);
+ dropdown = createComponent(editor);
+ });
+
+ it("is a split button whose action opens the assistant", () => {
+ const showSpy = vi.spyOn(editor.plugins.get(AiAssistantUI), "show");
+
+ expect(dropdown.buttonView).toBeInstanceOf(SplitButtonView);
+ expect(dropdown.buttonView.label).toBe("AI assistant");
+ expect(dropdown.buttonView.icon).toContain("<svg");
+
+ dropdown.buttonView.fire("execute");
+ expect(showSpy).toHaveBeenCalled();
+ });
+
+ it("lists every configured action under its group", () => {
+ const groups = quickActionGroups(dropdown);
+
+ expect(groups.map((group) => ({
+ label: group.label,
+ actions: group.buttons.map((button) => button.label)
+ }))).toEqual([
+ { label: "Edit or review", actions: ["Fix typos", "Make shorter"] },
+ { label: "Generate", actions: ["Write something"] }
+ ]);
+ });
+
+ it("gates the content-requiring actions on the selection", () => {
+ const [fixTypos, , write] = quickActionButtons(dropdown);
+
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ expect(fixTypos.isEnabled).toBe(false);
+ expect(write.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 () => {
+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");
+ const [fixTypos] = quickActionButtons(dropdown);
+
+ fixTypos.fire("execute");
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+
+ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "foo" });
+
+ const balloon = editor.plugins.get(ContextualBalloon);
+ expect(balloon.visibleView).not.toBeNull();
+ });
+
+ it("closes itself off while a run is in flight", async () => {
+ let release = () => {};
+ const editorWithSlowStream = await createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {
+ aiAssistant: {
+ sanitizeHtml,
+ quickActions: QUICK_ACTIONS,
+ stream: () => new Promise<void>((resolve) => {
+ release = resolve;
+ })
+ }
+ });
+ const slowDropdown = createComponent(editorWithSlowStream);
+
+ setModelData(editorWithSlowStream.model, "<paragraph>[foo]</paragraph>");
+ expect(slowDropdown.isEnabled).toBe(true);
+
+ const [fixTypos] = quickActionButtons(slowDropdown);
+ fixTypos.fire("execute");
+
+ await vi.waitFor(() => expect(slowDropdown.isEnabled).toBe(false));
+ release();
+ await vi.waitFor(() => expect(slowDropdown.isEnabled).toBe(true));
+ });
+ });
+
+ it("is disabled when no LLM provider is configured", async () => {
+ const editor = await createEditor(QUICK_ACTIONS);
+ expect(createComponent(editor).isEnabled).toBe(false);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index c59cd68976..dda199c116 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -1,16 +1,25 @@
import {
+ addListToDropdown,
ButtonView,
CKEditorError,
clickOutsideHandler,
+ Collection,
ContextualBalloon,
+ createDropdown,
Plugin,
+ SplitButtonView,
+ ViewModel,
+ type DropdownView,
+ type ListDropdownButtonDefinition,
+ type ListDropdownItemDefinition,
+ type Locale,
type ModelNode,
type ModelRange
} from "ckeditor5";
-import type { AiCompletionUsage } from "./ai_assistant_config.js";
+import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup } 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 AiAssistantFormView from "./ai_assistant_form.js";
import { stripMarkdownFences } from "./ai_html.js";
import aiIcon from "./theme/icons/ai.svg?raw";
import "./theme/ai_assistant.css";
@@ -22,8 +31,8 @@ import "./theme/ai_assistant.css";
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 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.
*
* 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
@@ -39,9 +48,20 @@ export default class AiAssistantUI extends Plugin {
return "AiAssistantUI" as const;
}
+ /**
+ * Whether a run is in flight. Observable, because the toolbar entry closes itself off while
+ * the assistant is busy — a second run would stream into the same preview.
+ */
+ declare public isStreaming: boolean;
+ /**
+ * Whether there is content for a quick action to work on: a non-collapsed selection, or, once
+ * the assistant is open, whatever it captured — after a run, the response being chained on.
+ * Gates the `requiresContent` actions in the toolbar menu.
+ */
+ declare public hasContext: boolean;
+
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 = "";
@@ -54,25 +74,103 @@ export default class AiAssistantUI extends Plugin {
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);
+ this.set("isStreaming", false);
+ this.set("hasContext", false);
- buttonView.set({
- label: t("AI assistant"),
- icon: aiIcon,
- tooltip: true
- });
+ editor.ui.componentFactory.add("aiAssistant", (locale) => this._createToolbarComponent(locale));
- /* v8 ignore next -- AiAssistantEditing always registers the command (it is required by this plugin) */
- if (command) {
- buttonView.bind("isEnabled").to(command, "isEnabled");
- }
+ // While the balloon 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());
+ }
+
+ /**
+ * The toolbar entry. Its main action opens the assistant on the selection; its menu lists the
+ * host's quick actions, grouped as configured, and picking one opens the assistant and runs
+ * that instruction straight away — the free-form prompt is one way in, not the only one.
+ *
+ * With no quick actions configured there is nothing to hang off an arrow, so the component
+ * degrades to a plain button.
+ */
+ private _createToolbarComponent(locale: Locale): ButtonView | DropdownView {
+ const groups = this.editor.config.get("aiAssistant")?.quickActions ?? [];
+ return groups.length
+ ? this._createQuickActionsDropdown(locale, groups)
+ : this._createAssistantButton(locale);
+ }
+
+ private _createAssistantButton(locale: Locale): ButtonView {
+ const command = this.editor.commands.get("aiAssistant");
+ const buttonView = new ButtonView(locale);
+
+ buttonView.set({
+ label: locale.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, "isStreaming", isAvailable);
+ }
+ this.listenTo(buttonView, "execute", () => this.editor.execute("aiAssistant"));
+
+ return buttonView;
+ }
- this.listenTo(buttonView, "execute", () => editor.execute("aiAssistant"));
- return buttonView;
+ /**
+ * The split button: the icon opens the assistant, the arrow opens the quick actions. Actions
+ * marked `requiresContent` stay disabled until there is something to work on — a selection, or
+ * a response to chain on.
+ */
+ private _createQuickActionsDropdown(locale: Locale, groups: AiQuickActionGroup[]): DropdownView {
+ const command = this.editor.commands.get("aiAssistant");
+ const dropdownView = createDropdown(locale, SplitButtonView);
+ const splitButtonView = dropdownView.buttonView;
+
+ splitButtonView.set({
+ label: locale.t("AI assistant"),
+ icon: aiIcon,
+ tooltip: true
});
+ // A dropdown passes `isEnabled` down to its button, so this covers both halves of the
+ // split button.
+ /* v8 ignore next -- AiAssistantEditing always registers the command (it is required by this plugin) */
+ if (command) {
+ dropdownView.bind("isEnabled").to(command, "isEnabled", this, "isStreaming", isAvailable);
+ }
+ this.listenTo(splitButtonView, "execute", () => this.editor.execute("aiAssistant"));
+
+ 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(dropdownView, items);
+ dropdownView.class = "ck-ai-assistant-quick-actions";
+
+ // Only the list items reach this: a split button delegates its own `execute` to itself,
+ // 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);
+ });
+
+ return dropdownView;
}
public override destroy(): void {
@@ -101,7 +199,7 @@ export default class AiAssistantUI extends Plugin {
: editor.data.stringify(model.getSelectedContent(selection));
this._previousContext = this._context;
this._cumulative = "";
- form.hasContext = !!this._context;
+ this._updateHasContext();
const range = selection.getFirstRange();
/* v8 ignore next -- the document selection always has at least one range */
@@ -122,10 +220,7 @@ export default class AiAssistantUI extends Plugin {
}
const editor = this.editor;
- const form = new AiAssistantFormView(
- editor.locale,
- editor.config.get("aiAssistant")?.quickActions ?? []
- );
+ const form = new AiAssistantFormView(editor.locale);
this._formView = form;
form.on("submit", () => {
@@ -135,9 +230,6 @@ export default class AiAssistantUI extends Plugin {
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"));
@@ -180,13 +272,13 @@ export default class AiAssistantUI extends Plugin {
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) {
+ if (!stream || this.isStreaming) {
return;
}
this._previousContext = this._context;
this._lastQuery = query;
- this._streaming = true;
+ this.isStreaming = true;
this._cumulative = "";
form.beginStreaming();
@@ -239,7 +331,7 @@ export default class AiAssistantUI extends Plugin {
if (pendingHtml !== null) {
render(pendingHtml);
}
- this._streaming = false;
+ this.isStreaming = false;
this._abortController = null;
}
@@ -248,7 +340,7 @@ export default class AiAssistantUI extends Plugin {
this._context = this._cumulative;
}
// A response counts as content, so content-requiring quick actions unlock for chaining.
- form.hasContext = !!this._context;
+ this._updateHasContext();
form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage, this._formatUsage(usage));
}
@@ -364,6 +456,11 @@ export default class AiAssistantUI extends Plugin {
this._abortController?.abort();
this._cumulative = "";
+ // Dropping the captured context hands the quick actions back to the selection; keeping it
+ // would leave them enabled over a closed assistant that has nothing to work on.
+ this._context = "";
+ this._previousContext = "";
+ this._updateHasContext();
if (editor.model.markers.has(AI_TARGET_MARKER)) {
editor.model.change((writer) => writer.removeMarker(AI_TARGET_MARKER));
@@ -375,6 +472,14 @@ export default class AiAssistantUI extends Plugin {
editor.editing.view.focus();
}
+ /**
+ * What the quick actions are offered against: whatever the assistant captured while open, or
+ * the selection once it is closed.
+ */
+ private _updateHasContext(): void {
+ this.hasContext = !!this._context || !this.editor.model.document.selection.isCollapsed;
+ }
+
private _getBalloonPosition() {
const editor = this.editor;
return {
@@ -390,3 +495,11 @@ export default class AiAssistantUI extends Plugin {
};
}
}
+
+/**
+ * Whether the toolbar entry can be used: the command is enabled (an LLM provider is configured)
+ * and no run is in flight.
+ */
+function isAvailable(isEnabled: boolean, isStreaming: boolean): boolean {
+ return isEnabled && !isStreaming;
+}
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
index 74ff010c36..b169ee8d66 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -27,8 +27,7 @@
gap: var(--ck-spacing-small);
}
-/* The quick-actions list is long (four groups); scroll it rather than overflow the screen. */
-.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row .ck-dropdown__panel {
+.ck.ck-dropdown.ck-ai-assistant-quick-actions .ck-dropdown__panel {
max-height: 320px;
overflow-y: auto;
}