Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(client): put the AI quick actions in the editor's right-click menu
Elian Doranad8af366d826
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.tsindex 531400bce2..f47c339d01 100644--- a/apps/client/src/menus/electron_context_menu.ts+++ b/apps/client/src/menus/electron_context_menu.ts@@ -7,6 +7,7 @@ import options from "../services/options.js";import server from "../services/server.js";import utils from "../services/utils.js";import contextMenu, { type MenuItem } from "./context_menu.js";+import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";function setupContextMenu() {const eApi = window.electronApi;@@ -15,12 +16,17 @@ function setupContextMenu() {const isMac = window.glob.platform === "darwin";const platformModifier = isMac ? "Meta" : "Ctrl";- api.onContextMenu((params) => {+ api.onContextMenu(async (params) => {const { editFlags } = params;const hasText = params.selectionText.trim().length > 0;const items: MenuItem<CommandNames>[] = [];+ // Resolved before the menu is built rather than lazily in a handler: the rows it produces+ // depend on how the editor answers, and `isEditable` keeps the lookup off every click that+ // lands somewhere a completion could not be committed anyway (a read-only note, the tree).+ const aiActions = params.isEditable ? await buildAiActionsMenuItem() : null;+if (params.misspelledWord) {for (const suggestion of params.dictionarySuggestions) {items.push({@@ -40,6 +46,10 @@ function setupContextMenu() {items.push({ kind: "separator" });}+ if (aiActions) {+ items.push(aiActions, { kind: "separator" });+ }+if (params.isEditable) {items.push({enabled: editFlags.canCut && hasText,@@ -182,26 +192,9 @@ function setupContextMenu() {* dialogs, plain inputs) we fall back to cloning the DOM range.*/export async function getSelectedHtmlForMarkdown(): Promise<string> {- const note = appContext.tabManager.getActiveContextNote();-- if (note?.type === "text") {- try {- const editor = await appContext.tabManager.getActiveContext()?.getTextEditor();- const domRoot = editor?.editing.view.getDomRoot();- const anchorNode = window.getSelection()?.anchorNode;-- // Only trust the editor's model selection when the live DOM selection is- // actually inside the editor; otherwise a stale editor selection would win- // over what the user right-clicked (e.g. selected text in a dialog).- if (editor && domRoot && anchorNode && domRoot.contains(anchorNode)) {- const selectedHtml = editor.getSelectedHtml();- if (selectedHtml) return selectedHtml;- }- } catch (error) {- // Editor not ready or the request timed out — fall through to the DOM clone.- console.error("Failed to read selection from the text editor:", error);- }- }+ const editor = await getTextEditorAtSelection();+ const selectedHtml = editor?.getSelectedHtml();+ if (selectedHtml) return selectedHtml;const selection = window.getSelection();if (!selection || !selection.rangeCount) return "";diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsnew file mode 100644index 0000000000..b4909fecf9--- /dev/null+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -0,0 +1,209 @@+import type { AiQuickAction, AiQuickActionGroup } from "@triliumnext/ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++const h = vi.hoisted(() => {+ const tabManager = {+ activeNote: null as { type: string } | null,+ activeContext: null as { getTextEditor: () => Promise<unknown> } | null,+ getActiveContextNote: () => tabManager.activeNote,+ getActiveContext: () => tabManager.activeContext+ };+ return { tabManager };+});++vi.mock("../components/app_context.js", () => ({ default: { tabManager: h.tabManager } }));+vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));++import type { MenuCommandItem, MenuItem } from "./context_menu.js";+import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";++const { tabManager } = h;++const GROUPS: AiQuickActionGroup[] = [+ {+ id: "edit",+ label: "Edit or review",+ actions: [{ id: "fixTypos", label: "Fix typos", prompt: "…", iconClass: "bx bx-check-double" }]+ },+ {+ id: "generate",+ label: "Generate",+ actions: [{ id: "draft", label: "Draft", prompt: "…", requiresContent: false }]+ },+ {+ id: "adjust",+ label: "Adjust",+ submenu: true,+ iconClass: "bx bx-ruler",+ actions: [{ id: "makeShorter", label: "Shorter", prompt: "…" }]+ },+ {+ id: "tone",+ label: "Change tone",+ submenu: true,+ actions: [{ id: "casual", label: "Casual", prompt: "…" }]+ }+];++/** The pieces of `AiAssistantUI` and the editor that the menu builder reads. */+function fakeEditor({+ domRoot,+ groups = GROUPS,+ hasContext = true,+ isStreaming = false,+ isEnabled = true,+ hasPlugin = true+}: {+ domRoot: Node | null;+ groups?: AiQuickActionGroup[];+ hasContext?: boolean;+ isStreaming?: boolean;+ isEnabled?: boolean;+ hasPlugin?: boolean;+}) {+ const ui = { hasContext, isStreaming, runQuickAction: vi.fn() };+ const editor = {+ editing: { view: { getDomRoot: () => domRoot } },+ plugins: { has: () => hasPlugin, get: () => ui },+ commands: { get: () => ({ isEnabled }) },+ config: { get: () => ({ quickActions: groups }) },+ execute: vi.fn()+ };+ tabManager.activeNote = { type: "text" };+ tabManager.activeContext = { getTextEditor: () => Promise.resolve(editor) };+ return { editor, ui };+}++/** Points `window.getSelection()` at `anchorNode`. */+function setSelection(anchorNode: Node | null) {+ vi.spyOn(window, "getSelection").mockReturnValue({ anchorNode } as unknown as Selection);+}++function titles(items: MenuItem<string>[]) {+ return items.map((item) => ("kind" in item ? `--- ${item.kind} ---` : item.title));+}++function commandItems(items: MenuItem<string>[]) {+ return items.filter((item) => !("kind" in item)) as MenuCommandItem<string>[];+}++describe("getTextEditorAtSelection", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ tabManager.activeNote = null;+ tabManager.activeContext = null;+ });++ it("returns the editor only when the selection is inside its DOM root", async () => {+ const root = document.createElement("div");+ const inside = document.createTextNode("hello");+ root.appendChild(inside);++ const { editor } = fakeEditor({ domRoot: root });+ setSelection(inside);+ expect(await getTextEditorAtSelection()).toBe(editor);++ // Same editor, but the click landed in a dialog rather than in the note.+ setSelection(document.createTextNode("elsewhere"));+ expect(await getTextEditorAtSelection()).toBeNull();+ });++ it("returns null for a non-text note, and swallows a failing editor lookup", async () => {+ setSelection(document.createTextNode("hello"));++ tabManager.activeNote = { type: "code" };+ tabManager.activeContext = { getTextEditor: () => Promise.reject(new Error("timed out")) };+ expect(await getTextEditorAtSelection()).toBeNull();++ tabManager.activeNote = { type: "text" };+ vi.spyOn(console, "error").mockImplementation(() => {});+ expect(await getTextEditorAtSelection()).toBeNull();+ });+});++describe("buildAiActionsMenuItem", () => {+ /** The editable root the selection sits in, so every editor below is the one that was clicked. */+ let root: HTMLElement;++ beforeEach(() => {+ vi.restoreAllMocks();+ root = document.createElement("div");+ const anchor = document.createTextNode("hello");+ root.appendChild(anchor);+ setSelection(anchor);+ });++ function build(overrides: Omit<Parameters<typeof fakeEditor>[0], "domRoot"> = {}) {+ return fakeEditor({ domRoot: root, ...overrides });+ }++ it("mirrors the toolbar's grouping: inlined actions, submenus, and a rule between groups except between two submenus", async () => {+ build();+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;++ expect(item.title).toBe("ai_assistant.title");+ expect(titles(item.items ?? [])).toEqual([+ "ai_assistant.action_ask",+ "--- separator ---",+ "Fix typos",+ "--- separator ---",+ "Draft",+ "--- separator ---",+ "Adjust",+ "Change tone"+ ]);++ const adjust = commandItems(item.items ?? []).find((i) => i.title === "Adjust");+ expect(adjust?.uiIcon).toBe("bx bx-ruler");+ expect(titles(adjust?.items ?? [])).toEqual(["Shorter"]);+ });++ it("disables the actions that need content — and the submenus whose actions all do", async () => {+ build({ hasContext: false });+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;+ const enabled = Object.fromEntries(commandItems(item.items ?? []).map((i) => [i.title, i.enabled]));++ expect(enabled).toMatchObject({+ "ai_assistant.action_ask": undefined,+ "Fix typos": false,+ Draft: true,+ Adjust: false,+ "Change tone": false+ });+ });++ it("runs the picked action, and opens the free-form prompt from the first row", async () => {+ const { editor, ui } = build();+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;+ const rows = commandItems(item.items ?? []);++ rows[0].handler?.(rows[0], null as never);+ expect(editor.execute).toHaveBeenCalledWith("aiAssistant");++ const fixTypos = rows.find((i) => i.title === "Fix typos");+ fixTypos?.handler?.(fixTypos, null as never);+ expect(ui.runQuickAction).toHaveBeenCalledWith(+ expect.objectContaining({ id: "fixTypos" }) satisfies AiQuickAction+ );+ });++ it("degrades to a plain row with no quick actions configured", async () => {+ const { editor } = build({ groups: [] });+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;++ expect(item.items).toBeUndefined();+ item.handler?.(item, null as never);+ expect(editor.execute).toHaveBeenCalledWith("aiAssistant");+ });++ it("is absent while a run streams, without a provider, and where the plugin is not loaded", async () => {+ build({ isStreaming: true });+ expect(await buildAiActionsMenuItem()).toBeNull();++ build({ isEnabled: false });+ expect(await buildAiActionsMenuItem()).toBeNull();++ build({ hasPlugin: false });+ expect(await buildAiActionsMenuItem()).toBeNull();+ });+});diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsnew file mode 100644index 0000000000..9f682846c5--- /dev/null+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -0,0 +1,137 @@+import type { AiQuickAction, AiQuickActionGroup, CKTextEditor } from "@triliumnext/ckeditor5";++import type { CommandNames } from "../components/app_context.js";+import appContext from "../components/app_context.js";+import { t } from "../services/i18n.js";+import type { MenuItem } from "./context_menu.js";++/**+ * The "AI assistant" row of the text editor's right-click menu: the toolbar's split-button entry,+ * reproduced as a submenu — its main action first, then the same quick actions in the same groups,+ * separated the same way.+ *+ * Right-click is where Word, Pages and the Obsidian AI plugins all put this, and it is the one+ * place the feature can be reached without knowing that a toolbar button or a `/` command exists.+ * The menu is built per click and read from the same `config.aiAssistant.quickActions` the toolbar+ * renders, so the two cannot drift; unlike the toolbar's, its enablement is a snapshot rather than+ * an observable binding, which is all a menu that lives for one click needs.+ *+ * Returns `null` whenever the assistant is out of reach — the click was not inside a text editor,+ * no LLM provider is configured, or a run is already streaming into the one dialog it has.+ */+export async function buildAiActionsMenuItem(): Promise<MenuItem<CommandNames> | null> {+ const editor = await getTextEditorAtSelection();+ if (!editor?.plugins.has("AiAssistantUI")) {+ return null;+ }++ const ui = editor.plugins.get("AiAssistantUI");+ const command = editor.commands.get("aiAssistant");+ if (!command?.isEnabled || ui.isStreaming) {+ return null;+ }++ const quickActions = buildQuickActionItems(+ editor.config.get("aiAssistant")?.quickActions ?? [],+ ui.hasContext,+ (action) => ui.runQuickAction(action)+ );++ // With nothing to hang off it the toolbar entry degrades from a split button to a plain one,+ // and so does this: a submenu holding a single row is a worse way to click that same row.+ if (!quickActions.length) {+ return {+ title: t("ai_assistant.title"),+ uiIcon: "bx bx-bot",+ handler: () => editor.execute("aiAssistant")+ };+ }++ return {+ title: t("ai_assistant.title"),+ uiIcon: "bx bx-bot",+ items: [+ {+ title: t("ai_assistant.action_ask"),+ uiIcon: "bx bx-message-square-dots",+ handler: () => editor.execute("aiAssistant")+ },+ { kind: "separator" },+ ...quickActions+ ]+ };+}++/**+ * The quick actions as menu rows, laid out the way the toolbar's dropdown lays them out: a group+ * marked `submenu` opens one, an inlined group contributes its actions directly, and a rule is+ * drawn between groups except between two consecutive submenus, which read as one block of openers+ * already.+ *+ * @param hasContext whether there is content to work on, as the assistant reports it. Actions that+ * need content — every one Trilium ships — are disabled without it, and so is a+ * submenu whose actions all do.+ */+function buildQuickActionItems(+ groups: AiQuickActionGroup[],+ hasContext: boolean,+ run: (action: AiQuickAction) => void+): MenuItem<CommandNames>[] {+ const canRun = (action: AiQuickAction) => action.requiresContent === false || hasContext;+ const items: MenuItem<CommandNames>[] = [];++ for (const [index, group] of groups.entries()) {+ const children = group.actions.map((action) => ({+ title: action.label,+ uiIcon: action.iconClass,+ enabled: canRun(action),+ handler: () => run(action)+ }));++ if (group.submenu) {+ items.push({+ title: group.label,+ uiIcon: group.iconClass,+ enabled: group.actions.some(canRun),+ items: children+ });+ } else {+ items.push(...children);+ }++ const next = groups[index + 1];+ if (next && !(group.submenu && next.submenu)) {+ items.push({ kind: "separator" });+ }+ }++ return items;+}++/**+ * The text editor the live DOM selection sits in, or `null` when it sits anywhere else.+ *+ * The containment check is what makes this answer the click rather than the tab: the active note+ * can be a text note while the selection is in a dialog or a plain input, and the editor would+ * happily report its own stale model selection for it.+ */+export async function getTextEditorAtSelection(): Promise<CKTextEditor | null> {+ if (appContext.tabManager.getActiveContextNote()?.type !== "text") {+ return null;+ }++ try {+ const editor = await appContext.tabManager.getActiveContext()?.getTextEditor();+ const domRoot = editor?.editing.view.getDomRoot();+ const anchorNode = window.getSelection()?.anchorNode;++ if (editor && domRoot && anchorNode && domRoot.contains(anchorNode)) {+ return editor;+ }+ } catch (error) {+ // Editor not ready or the request timed out.+ console.error("Failed to read the text editor at the selection:", error);+ }++ return null;+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex bcace755ba..7b55d89c45 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2834,6 +2834,8 @@"play_video": "Play video"},"ai_assistant": {+ "title": "AI assistant",+ "action_ask": "Ask AI…","group_edit": "Edit or review","group_generate": "Generate","group_adjust": "Adjust",@@ -3976,7 +3978,8 @@"type-the-content-here": "Type the content here...","undefined-custom-task-state": "Undefined custom task state","url": "URL",- "warning": "Warning"+ "warning": "Warning",+ "working": "Working…"},"task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",