Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): add quick actions to the AI assistant

Elian Doran72444ecf9ae6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c4af93ab07..e5cbd0f9eb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2526,7 +2526,29 @@
"try_again": "Try again",
"result": "Result",
"changes": "Changes",
- "tokens": "tokens"
+ "tokens": "tokens",
+ "quick_actions": "Quick actions",
+ "group_edit": "Edit or review",
+ "group_generate": "Generate",
+ "group_tone": "Change tone",
+ "group_translate": "Translate",
+ "action_fix_typos": "Fix typos",
+ "action_improve_writing": "Improve writing",
+ "action_make_shorter": "Make shorter",
+ "action_make_longer": "Make longer",
+ "action_simplify": "Simplify language",
+ "action_summarize": "Summarize",
+ "action_continue": "Continue writing",
+ "tone_professional": "Professional",
+ "tone_casual": "Casual",
+ "tone_direct": "Direct",
+ "tone_friendly": "Friendly",
+ "lang_english": "English",
+ "lang_german": "German",
+ "lang_spanish": "Spanish",
+ "lang_french": "French",
+ "lang_romanian": "Romanian",
+ "lang_chinese": "Simplified Chinese"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
index dbff01f6cf..7b6d2d5402 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
@@ -1,6 +1,7 @@
-import type { AiCompletionUsage, AiStreamFunction } from "@triliumnext/ckeditor5";
+import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";
import type { LlmChatConfig, LlmMessage, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
+import { t } from "../../../services/i18n.js";
import { streamChatCompletion } from "../../../services/llm_chat.js";
import options from "../../../services/options.js";
@@ -59,6 +60,73 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
};
}
+/**
+ * The predefined instructions for the balloon's "Quick actions" dropdown, modelled on the premium
+ * AI assistant's default command set. Labels are translated here (the plugin renders them as
+ * given); prompts stay English — they are instructions to the model, not UI.
+ */
+export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
+ return [
+ {
+ id: "edit",
+ label: t("ai_assistant.group_edit"),
+ actions: [
+ action("fixTypos", t("ai_assistant.action_fix_typos"),
+ "Fix all spelling, grammar and punctuation mistakes. Do not change the meaning, tone or formatting."),
+ action("improveWriting", t("ai_assistant.action_improve_writing"),
+ "Improve the writing: fix mistakes, tighten the phrasing and apply good writing practices without changing the meaning."),
+ action("makeShorter", t("ai_assistant.action_make_shorter"),
+ "Shorten this content by removing repetition and non-essential details, without losing key information."),
+ action("makeLonger", t("ai_assistant.action_make_longer"),
+ "Expand this content with more detail and clearer explanations, keeping the original meaning."),
+ action("simplify", t("ai_assistant.action_simplify"),
+ "Rewrite this content in simpler language so that it is easier to understand.")
+ ]
+ },
+ {
+ id: "generate",
+ label: t("ai_assistant.group_generate"),
+ actions: [
+ action("summarize", t("ai_assistant.action_summarize"),
+ "Summarize this content into one short paragraph containing only the key ideas and conclusions."),
+ action("continue", t("ai_assistant.action_continue"),
+ "Continue writing from the end of the provided content, staying on topic and matching its style. Keep the continuation brief.")
+ ]
+ },
+ {
+ id: "tone",
+ label: t("ai_assistant.group_tone"),
+ actions: [
+ action("professional", t("ai_assistant.tone_professional"),
+ "Rewrite this content in a polished, formal, professional tone without changing the meaning."),
+ action("casual", t("ai_assistant.tone_casual"),
+ "Rewrite this content in a casual, conversational tone without changing the meaning."),
+ action("direct", t("ai_assistant.tone_direct"),
+ "Rewrite this content in a direct tone, keeping only the essential information."),
+ action("friendly", t("ai_assistant.tone_friendly"),
+ "Rewrite this content in a warm, friendly tone without changing the meaning.")
+ ]
+ },
+ {
+ id: "translate",
+ label: t("ai_assistant.group_translate"),
+ actions: [
+ action("translateEnglish", t("ai_assistant.lang_english"), "Translate the content to English."),
+ action("translateGerman", t("ai_assistant.lang_german"), "Translate the content to German."),
+ action("translateSpanish", t("ai_assistant.lang_spanish"), "Translate the content to Spanish."),
+ action("translateFrench", t("ai_assistant.lang_french"), "Translate the content to French."),
+ action("translateRomanian", t("ai_assistant.lang_romanian"), "Translate the content to Romanian."),
+ action("translateChinese", t("ai_assistant.lang_chinese"), "Translate the content to Simplified Chinese.")
+ ]
+ }
+ ];
+}
+
+/** Shorthand for a quick-action entry; all defaults require content to work on. */
+function action(id: string, label: string, prompt: string): AiQuickAction {
+ return { id, label, prompt };
+}
+
/**
* 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,
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 363f565504..02d9ef7327 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -13,7 +13,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 buildAiAssistantStream, { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
import { buildToolbarConfig } from "./toolbar.js";
export const OPEN_SOURCE_LICENSE_KEY = "GPL";
@@ -187,7 +187,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
stream: buildAiAssistantStream(),
// The "Changes" review view: the same HTML-aware inline diff (`<ins>`/`<del>`
// markup) the revisions dialog uses.
- diff: (oldHtml: string, newHtml: string) => HtmlDiff.execute(oldHtml, newHtml)
+ diff: (oldHtml: string, newHtml: string) => HtmlDiff.execute(oldHtml, newHtml),
+ quickActions: buildAiAssistantQuickActions()
},
htmlSupport: {
allow: JSON.parse(options.get("allowedHtmlTags"))
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index e17e20a530..21a38732d0 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -14,7 +14,7 @@ export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";
-export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiQuickAction, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
export * from "./utils.js";
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index 4162846a1d..c8da5789a5 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -55,6 +55,32 @@ 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.
+ */
+export interface AiQuickAction {
+ id: string;
+ /** The label shown in the dropdown, 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.
+ */
+ requiresContent?: boolean;
+}
+
+/** A labelled group of quick actions, rendered as a group in the dropdown. */
+export interface AiQuickActionGroup {
+ id: string;
+ /** The group heading, already translated by the host. */
+ label: string;
+ actions: AiQuickAction[];
+}
+
export interface AiAssistantConfig {
/**
* Streams a completion for a request. When absent (no LLM provider configured), the whole
@@ -69,4 +95,11 @@ export interface AiAssistantConfig {
* would render as a sea of deletions).
*/
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.
+ */
+ 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 c76544f0d5..cd02bfdde6 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,16 +1,34 @@
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(): AiAssistantFormView {
- form = new AiAssistantFormView(new Locale(), (_key, fallback) => fallback);
+function makeForm(quickActions: AiQuickActionGroup[] = []): AiAssistantFormView {
+ form = new AiAssistantFormView(new Locale(), (_key, fallback) => fallback, quickActions);
form.render();
return form;
}
+const SAMPLE_ACTIONS: AiQuickActionGroup[] = [{
+ id: "edit",
+ label: "Edit or review",
+ actions: [
+ { id: "fixTypos", label: "Fix typos", prompt: "Fix all mistakes." },
+ { id: "generate", label: "Generate", prompt: "Write something.", requiresContent: false }
+ ]
+}];
+
+/** The rendered quick-action item buttons, in definition order. */
+function quickActionButtons(): HTMLButtonElement[] {
+ form.quickActionsDropdownView.isOpen = true;
+ const panel = form.quickActionsDropdownView.panelView.element;
+ return Array.from(panel?.querySelectorAll("button") ?? []);
+}
+
function previewHtml(): string {
return form.previewView.element?.innerHTML ?? "";
}
@@ -102,6 +120,37 @@ 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 7f20e5a7fe..7a11d6c195 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -1,5 +1,8 @@
import {
+ addListToDropdown,
ButtonView,
+ Collection,
+ createDropdown,
createLabeledInputText,
FocusCycler,
FocusTracker,
@@ -8,11 +11,17 @@ 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";
+
/** Resolves a translation key, falling back to the given English text. See `translate.ts`. */
type Translate = (key: string, fallback: string) => string;
@@ -26,6 +35,12 @@ 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
@@ -46,6 +61,11 @@ 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 = "";
@@ -54,6 +74,7 @@ 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;
@@ -68,7 +89,7 @@ export default class AiAssistantFormView extends View {
private readonly _focusables = new ViewCollection<FocusableView>();
private readonly _focusCycler: FocusCycler;
- constructor(locale: Locale, translate: Translate) {
+ constructor(locale: Locale, translate: Translate, quickActions: AiQuickActionGroup[] = []) {
super(locale);
this.set("phase", "prompt");
@@ -77,12 +98,14 @@ 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, translate("ai_assistant.result", "Result"), "result");
this.changesToggleView = this._createViewModeButton(locale, translate("ai_assistant.changes", "Changes"), "changes");
+ this.quickActionsDropdownView = this._createQuickActionsDropdown(locale, translate, quickActions);
this.promptInputView = this._createPromptInput(locale, translate);
this.sendButtonView = this._createSendButton(locale, translate);
this.previewView = new AiPreviewView(locale);
@@ -131,7 +154,7 @@ export default class AiAssistantFormView extends View {
{
tag: "div",
attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },
- children: [this.promptInputView, this.sendButtonView]
+ children: [this.quickActionsDropdownView, this.promptInputView, this.sendButtonView]
},
{
tag: "div",
@@ -177,6 +200,7 @@ export default class AiAssistantFormView extends View {
const focusables = [
this.resultToggleView,
this.changesToggleView,
+ this.quickActionsDropdownView,
this.promptInputView,
this.sendButtonView,
this.stopButtonView,
@@ -259,6 +283,53 @@ 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, translate: Translate, groups: AiQuickActionGroup[]) {
+ const dropdown = createDropdown(locale);
+
+ dropdown.buttonView.set({
+ label: translate("ai_assistant.quick_actions", "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.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index 8c8cbc70d6..8d864b3d78 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -10,7 +10,7 @@ import {
import { translate } from "../translate.js";
import type { AiCompletionUsage } from "./ai_assistant_config.js";
import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
-import AiAssistantFormView from "./ai_assistant_form.js";
+import AiAssistantFormView, { type AiQuickActionEvent } from "./ai_assistant_form.js";
import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";
import aiIcon from "./theme/icons/ai.svg?raw";
import "./theme/ai_assistant.css";
@@ -100,6 +100,7 @@ export default class AiAssistantUI extends Plugin {
: editor.data.stringify(model.getSelectedContent(selection));
this._previousContext = this._context;
this._cumulative = "";
+ form.hasContext = !!this._context;
const range = selection.getFirstRange();
/* v8 ignore next -- the document selection always has at least one range */
@@ -120,7 +121,11 @@ export default class AiAssistantUI extends Plugin {
}
const editor = this.editor;
- const form = new AiAssistantFormView(editor.locale, (key, fallback) => translate(editor, key, fallback));
+ const form = new AiAssistantFormView(
+ editor.locale,
+ (key, fallback) => translate(editor, key, fallback),
+ editor.config.get("aiAssistant")?.quickActions ?? []
+ );
this._formView = form;
form.on("submit", () => {
@@ -130,6 +135,9 @@ 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"));
@@ -239,6 +247,8 @@ export default class AiAssistantUI extends Plugin {
// Follow-up queries chain on the response ("now make it shorter"), premium-style.
this._context = this._cumulative;
}
+ // A response counts as content, so content-requiring quick actions unlock for chaining.
+ form.hasContext = !!this._context;
form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage, this._formatUsage(usage));
}
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 a8dac876da..74ff010c36 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -27,6 +27,12 @@
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 {
+ max-height: 320px;
+ overflow-y: auto;
+}
+
.ck.ck-ai-assistant-form .ck-ai-assistant-form__prompt-row .ck-labeled-field-view {
flex-grow: 1;
}