Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): offer the AI quick actions in the slash palette

Elian Doranc08902348f54
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 13ce462d19..0289e69a4b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2838,6 +2838,8 @@
"group_generate": "Generate",
"group_tone": "Change tone",
"group_translate": "Translate",
+ "command_tone": "Change tone to {{tone}}",
+ "command_translate": "Translate to {{language}}",
"action_fix_typos": "Fix typos",
"action_improve_writing": "Improve writing",
"action_make_shorter": "Make shorter",
@@ -3821,6 +3823,7 @@
"text-editor": {
"ck": {
"admonition": "Admonition",
+ "ai-0": "AI: %0",
"ai-assistant": "AI assistant",
"align-text-to-the-center": "Align text to the center",
"align-text-to-the-left": "Align text to the left",
@@ -3833,6 +3836,7 @@
"anchor-toolbar": "Anchor toolbar",
"anchor-widget": "anchor widget",
"anchors": "Anchors",
+ "applies-to-the-current-paragraph": "Applies to the current paragraph.",
"ask-ai-to": "Ask AI to…",
"ask-ai-to-rewrite-the-selection-or-generate-new-content": "Ask AI to rewrite the selection or generate new content.",
"box-size": "Box size",
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
index 94dc908196..104f7e7bd8 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
@@ -1,7 +1,13 @@
import type { LlmChatConfig } from "@triliumnext/commons";
import { beforeEach, describe, expect, it, vi } from "vitest";
-vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key }));
+// Keys stand in for their translations; a key with interpolation renders as `key(name=value)`, so
+// a composed label shows both the key it went through and what was substituted into it.
+vi.mock("../../../services/i18n.js", () => ({
+ t: (key: string, values?: Record<string, string>) => (values
+ ? `${key}(${Object.entries(values).map(([name, value]) => `${name}=${value}`).join(",")})`
+ : key)
+}));
vi.mock("../../../services/options.js", () => ({
default: { getJson: () => storedProviders }
}));
@@ -13,7 +19,7 @@ vi.mock("../../../services/llm_chat.js", () => ({
})
}));
-import buildAiAssistantStream from "./ai_assistant_stream.js";
+import buildAiAssistantStream, { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
/** The `llmProviders` option as the mocked `options.getJson` will return it. */
let storedProviders: unknown = null;
@@ -74,3 +80,33 @@ describe("buildAiAssistantStream", () => {
expect(await runOnce()).toEqual({ provider: "openai", providerId: "cfg-openai" });
});
});
+
+describe("buildAiAssistantQuickActions", () => {
+ function actions(groupId: string) {
+ const group = buildAiAssistantQuickActions().find((candidate) => candidate.id === groupId);
+ if (!group) {
+ throw new Error(`no quick-action group with id "${groupId}"`);
+ }
+ return group.actions;
+ }
+
+ // A tone or a language means nothing on its own once it is away from its group heading, which
+ // is where the `/` palette shows it.
+ it("composes a standalone command label for the tones and the languages", () => {
+ const direct = actions("tone").find((action) => action.id === "direct");
+ expect(direct?.label).toBe("ai_assistant.tone_direct");
+ expect(direct?.commandLabel).toBe("ai_assistant.command_tone(tone=ai_assistant.tone_direct)");
+
+ const romanian = actions("translate").find((action) => action.id === "translateRomanian");
+ expect(romanian?.label).toBe("ai_assistant.lang_romanian");
+ expect(romanian?.commandLabel).toBe("ai_assistant.command_translate(language=ai_assistant.lang_romanian)");
+ // The instruction is not translated: it is addressed to the model, not to the user.
+ expect(romanian?.prompt).toBe("Translate the content to Romanian.");
+ });
+
+ it("leaves the labels that already read as commands alone", () => {
+ for (const action of [ ...actions("edit"), ...actions("generate") ]) {
+ expect(action.commandLabel).toBeUndefined();
+ }
+ });
+});
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 1e98b4645c..a4672de9b1 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
@@ -97,13 +97,13 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
id: "tone",
label: t("ai_assistant.group_tone"),
actions: [
- action("professional", t("ai_assistant.tone_professional"),
+ toneAction("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"),
+ toneAction("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"),
+ toneAction("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"),
+ toneAction("friendly", t("ai_assistant.tone_friendly"),
"Rewrite this content in a warm, friendly tone without changing the meaning.")
]
},
@@ -111,12 +111,12 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
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.")
+ translateAction("translateEnglish", t("ai_assistant.lang_english"), "Translate the content to English."),
+ translateAction("translateGerman", t("ai_assistant.lang_german"), "Translate the content to German."),
+ translateAction("translateSpanish", t("ai_assistant.lang_spanish"), "Translate the content to Spanish."),
+ translateAction("translateFrench", t("ai_assistant.lang_french"), "Translate the content to French."),
+ translateAction("translateRomanian", t("ai_assistant.lang_romanian"), "Translate the content to Romanian."),
+ translateAction("translateChinese", t("ai_assistant.lang_chinese"), "Translate the content to Simplified Chinese.")
]
}
];
@@ -127,6 +127,21 @@ function action(id: string, label: string, prompt: string): AiQuickAction {
return { id, label, prompt };
}
+/**
+ * A tone or a language reads as a command only together with what its group heading says: the menu
+ * lists a bare "Direct" under "Change tone", while the `/` palette has to spell out "Change tone to
+ * Direct". Composed here rather than in the editor so that a locale can reorder the two halves —
+ * and pick the right preposition and case for the language name.
+ */
+function toneAction(id: string, tone: string, prompt: string): AiQuickAction {
+ return { id, label: tone, commandLabel: t("ai_assistant.command_tone", { tone }), prompt };
+}
+
+/** The prompt stays English and spelled out: the label is translated, the instruction is not. */
+function translateAction(id: string, language: string, prompt: string): AiQuickAction {
+ return { id, label: language, commandLabel: t("ai_assistant.command_translate", { language }), 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/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index b64acef13b..248359f8b6 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -64,6 +64,14 @@ export interface AiQuickAction {
id: string;
/** The label shown in the menu, already translated by the host. */
label: string;
+ /**
+ * The action phrased as a standalone command ("Translate to Romanian"), for the places that
+ * show it away from its group heading — the `/` palette, where the bare {@link label} the menu
+ * gets away with ("Romanian") would say nothing. Also translated by the host, since only it can
+ * word the composition; defaults to {@link label}, which is enough for an action whose label
+ * already reads as a command ("Fix typos").
+ */
+ commandLabel?: string;
/** The instruction sent to the model in place of a typed query. */
prompt: string;
/**
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index 0294d5b159..9e6f222676 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -496,12 +496,13 @@ describe("buildTriliumSlashCommands", () => {
let editor: ClassicEditor;
/** Records `execute()` calls and serves plugin lookups, standing in for the *target* editor. */
- function makeFakeEditor() {
+ function makeFakeEditor(commands: Record<string, unknown> = {}) {
const pluginInstances = new Map<unknown, unknown>();
const executeSpy = vi.fn();
const fake = {
execute: executeSpy,
- plugins: { get: (key: unknown) => pluginInstances.get(key) }
+ plugins: { get: (key: unknown) => pluginInstances.get(key) },
+ commands: { get: (name: string) => commands[name] }
} as unknown as Editor;
return { fake, executeSpy, pluginInstances };
}
@@ -620,6 +621,100 @@ describe("buildTriliumSlashCommands", () => {
expect(ids.filter((id) => id.startsWith("mermaid-sample-"))).toEqual([]);
});
+ describe("AI quick actions", () => {
+ /** The assistant requires one; nothing here renders a response, so identity will do. */
+ const sanitizeHtml = (html: string) => html;
+ const GROUPS = [
+ {
+ 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: "translate",
+ label: "Translate",
+ // A label that only reads as a command together with its group heading, which is
+ // why the host composes one.
+ actions: [ { id: "german", label: "German", commandLabel: "Translate to German", prompt: "Translate the content to German." } ]
+ }
+ ];
+
+ /**
+ * The palette only asks the editor whether the assistant is loaded and what it configured,
+ * so a stub keeps this spec off the plugin itself — the entries are the palette's own
+ * contribution, and the assistant has its own tests for what running one does.
+ */
+ function withAssistantLoaded(quickActions = GROUPS) {
+ editor.config.set("aiAssistant", { quickActions, sanitizeHtml });
+ const hasPlugin = editor.plugins.has.bind(editor.plugins);
+ vi.spyOn(editor.plugins, "has").mockImplementation(
+ (key) => key === "AiAssistantUI" || hasPlugin(key)
+ );
+ }
+
+ function aiEntries() {
+ return buildTriliumSlashCommands(editor).filter((entry) => entry.id.startsWith("ai-") && entry.id !== "ai-assistant");
+ }
+
+ // The prefix marks them out in a palette of insert-a-thing entries, and `commandLabel`
+ // wins over the bare label the menu shows under a group heading.
+ it("prefixes each configured action and says what it applies to", () => {
+ withAssistantLoaded();
+
+ expect(aiEntries().map((entry) => ({ id: entry.id, title: entry.title, description: entry.description }))).toEqual([
+ { id: "ai-fixTypos", title: "AI: Fix typos", description: "Applies to the current paragraph." },
+ { id: "ai-makeShorter", title: "AI: Make shorter", description: "Applies to the current paragraph." },
+ { id: "ai-german", title: "AI: Translate to German", description: "Applies to the current paragraph." }
+ ]);
+ });
+
+ it("answers to /ai through the prefix, and to its group's name through an alias", () => {
+ withAssistantLoaded();
+
+ expect(matchSlashCommands(aiEntries(), "ai").map((entry) => entry.id))
+ .toEqual([ "ai-fixTypos", "ai-makeShorter", "ai-german" ]);
+ // "Edit or review" is nowhere in "AI: Fix typos", so the group has to come along.
+ expect(matchSlashCommands(aiEntries(), "edit or").map((entry) => entry.id))
+ .toEqual([ "ai-fixTypos", "ai-makeShorter" ]);
+ });
+
+ it("hands the picked action to the assistant", () => {
+ withAssistantLoaded();
+ const { fake, pluginInstances } = makeFakeEditor();
+ const runQuickAction = vi.fn();
+ pluginInstances.set("AiAssistantUI", { runQuickAction });
+
+ aiEntries()[0].execute?.(fake);
+
+ expect(runQuickAction).toHaveBeenCalledWith(GROUPS[0].actions[0]);
+ });
+
+ it("is offered only while the assistant command is enabled", () => {
+ withAssistantLoaded();
+ const entry = aiEntries()[0];
+
+ expect(isSlashCommandEnabled(makeFakeEditor({ aiAssistant: { isEnabled: true } }).fake, entry)).toBe(true);
+ expect(isSlashCommandEnabled(makeFakeEditor({ aiAssistant: { isEnabled: false } }).fake, entry)).toBe(false);
+ // No LLM provider configured at all: the command is never registered.
+ expect(isSlashCommandEnabled(makeFakeEditor().fake, entry)).toBe(false);
+ });
+
+ it("contributes nothing when the assistant is not loaded", () => {
+ editor.config.set("aiAssistant", { quickActions: GROUPS, sanitizeHtml });
+
+ expect(aiEntries()).toEqual([]);
+ });
+
+ it("contributes nothing when the host configured no actions", () => {
+ withAssistantLoaded([]);
+
+ expect(aiEntries()).toEqual([]);
+ });
+ });
+
// The reason these moved out of the host: the host translator only ever resolved Trilium's own
// catalog, so strings CKEditor already translates — "Align left", "Page break" — stayed English.
it("translates through the editor, so CKEditor's own strings resolve too", async () => {
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index cc21aaa302..d2946e2771 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -396,10 +396,50 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
// state for balloon positioning.
setTimeout(() => (target.plugins.get(BookmarkUI) as unknown as { _showFormView(): void })._showFormView(), 0);
}
- }
+ },
+ ...buildAiQuickActionSlashCommands(editor)
];
}
+/**
+ * One entry per AI quick action the host configured ("Fix typos", "Translate to Romanian", …) —
+ * the same presets the toolbar's AI entry hangs off its arrow, reachable by name instead of by
+ * hunting through a menu.
+ *
+ * The `AI:` prefix keeps a palette full of insert-a-thing entries readable: without it "Summarize"
+ * sits among "Summary" and "Table" as if it inserted something, and there is no other cue that a
+ * dozen of these hand the paragraph to a language model. It doubles as the query that reaches the
+ * whole set, since `/ai` then matches every one of them by title.
+ *
+ * Only that prefix goes through `editor.t()`. The action's own wording arrives from the host
+ * already translated — it is the host that composes "Translate to Romanian" out of a group and a
+ * language, so it is the host that has to word it.
+ *
+ * The palette is typed at a collapsed caret, which is why a quick action run this way falls back
+ * to the caret's block — see `AiAssistantUI#runQuickAction`, and the description saying so.
+ * Enablement therefore only asks whether the feature is available at all: the pending `/query` is
+ * itself text in that block, so a content check here would answer "yes" no matter what.
+ */
+function buildAiQuickActionSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ if (!editor.plugins.has("AiAssistantUI")) {
+ return [];
+ }
+
+ const t = editor.locale.t;
+
+ return (editor.config.get("aiAssistant")?.quickActions ?? []).flatMap((group) =>
+ group.actions.map((action) => ({
+ id: `ai-${action.id}`,
+ title: t("AI: %0", action.commandLabel ?? action.label),
+ description: t("Applies to the current paragraph."),
+ aliases: [ group.label ],
+ icon: aiIcon,
+ isEnabled: (target: Editor) => target.commands.get("aiAssistant")?.isEnabled ?? false,
+ execute: (target: Editor) => target.plugins.get("AiAssistantUI").runQuickAction(action)
+ }))
+ );
+}
+
// Replaces CKEditor's built-in `bulletedList`/`numberedList`/`todoList` slash commands (removed via
// `removeCommands`), whose titles are Title Case, with sentence-case equivalents that run the same
// commands.