Skip to content

Build your personal knowledge base with Trilium Notes

feat(ai-assistant): let the user write their own quick actions

Elian Doran8a3a8479a2cb
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 075d5c10e0..39b04d6d1a 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -691,6 +691,7 @@
"snippet_description": "Description shown beside this code snippet where it is offered for insertion.",
"text_snippet": "Offers this text note as a snippet to insert into other text notes.",
"text_snippet_description": "Description shown beside this text snippet where it is offered for insertion.",
+ "ai_quick_action": "Offers this note as an instruction in the text editor's AI assistant menu. The title names the action, the content is the prompt.",
"execute_title": "Title of the tab this code note is executed from.",
"clipper_inbox": "Where the Web Clipper saves what it collects, instead of the day note.",
"clip_type": "Records how the Web Clipper made this note, e.g. <code>clippings</code>.",
@@ -2842,6 +2843,7 @@
"group_tone": "Change tone",
"group_reformat": "Reformat",
"group_translate": "Translate",
+ "group_custom": "Custom",
"command_make_shorter": "Make shorter",
"command_make_longer": "Make longer",
"command_simplify": "Simplify language",
diff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.ts
index 4a1b732475..b0093211dc 100644
--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts
+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts
@@ -110,6 +110,7 @@ export const ATTR_HELP: AttrHelpMap = {
snippetDescription: t("attribute_detail.snippet_description"),
textSnippet: t("attribute_detail.text_snippet"),
textSnippetDescription: t("attribute_detail.text_snippet_description"),
+ aiQuickAction: t("attribute_detail.ai_quick_action"),
executeTitle: t("attribute_detail.execute_title"),
clipperInbox: t("attribute_detail.clipper_inbox"),
clipType: t("attribute_detail.clip_type"),
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 18e6ae1457..a5443ba991 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -6,7 +6,7 @@ import froca from "../../../services/froca";
import link from "../../../services/link";
import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";
import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
-import { buildAiAssistantQuickActions } from "./ai_assistant_stream";
+import { useAiQuickActions } from "./ai_quick_actions";
import { buildConfig, BuildEditorOptions } from "./config";
export type BoxSize = "small" | "medium" | "full" | "expandable";
@@ -94,12 +94,13 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
// the tag list, for the same by-value reason as `customReplacements` above.
const [ htmlSupportEnabled ] = useTriliumOptionBool("textNoteHtmlSupportEnabled");
const [ allowedHtmlTags ] = useTriliumOption("allowedHtmlTags");
- // Deliberately *not* a rebuild trigger: the enabled content languages fill the AI assistant's
- // Translate submenu, which now offers the row that edits them — so the change is made from
- // inside the editor, several times over while the modal is open, and a rebuild each time would
- // cost the caret and the undo history of the note being written. Pushed into the live editor by
- // the effect below instead. The raw JSON, for the by-value reason above.
- const [ contentLanguages ] = useTriliumOption("languages");
+ // Deliberately *not* a rebuild trigger — pushed into the live editor by the effect below
+ // instead. The enabled content languages fill the assistant's Translate submenu, which now
+ // offers the row that edits them, so the change is made from inside the editor and several
+ // times over while the modal is open; the custom actions are notes, written and revised in the
+ // editor itself. A rebuild for either would cost the caret and the undo history of the note
+ // being written.
+ const quickActions = useAiQuickActions();
const [ editor, setEditor ] = useState<CKTextEditor>();
const { parentComponent, ntxId, note } = useNoteContext();
@@ -341,15 +342,14 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
}
}, [ editor, templates ]);
- // Likewise for the AI quick actions, whose Translate group lists the enabled content languages:
- // rebuilt from the current options and pushed into the live editor, so enabling a language shows
- // it in the menu without the note losing its undo history.
+ // Likewise for the AI quick actions: enabling a content language or writing a `#aiQuickAction`
+ // note shows up in the menu without the note being edited losing its undo history.
useEffect(() => {
if (!editor) return;
if (editor.plugins.has("AiAssistantUI")) {
- editor.plugins.get("AiAssistantUI").updateQuickActions(buildAiAssistantQuickActions());
+ editor.plugins.get("AiAssistantUI").updateQuickActions(quickActions);
}
- }, [ editor, contentLanguages ]);
+ }, [ editor, quickActions ]);
// React to notification warning callback.
diff --git a/apps/client/src/widgets/type_widgets/text/ai_quick_actions.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.spec.ts
new file mode 100644
index 0000000000..abe575bb6e
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.spec.ts
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+// The prompt of a text note is read out of its HTML through DOMParser, which happy-dom does not
+// traverse faithfully — the same reason `ai_assistant_stream.spec` pins itself to jsdom.
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../services/search.js", () => ({ default: { searchForNotes: vi.fn() } }));
+vi.mock("../../../services/froca.js", () => ({ default: { getNotes: vi.fn() } }));
+// `getAvailableLocales` is reached through the built-in groups, which come along for the ride.
+vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key, getAvailableLocales: () => [] }));
+vi.mock("../../../services/options.js", () => ({ default: { getJson: () => null } }));
+vi.mock("../../../components/app_context.js", () => ({ default: { triggerCommand: vi.fn() } }));
+// The hook is not under test here; importing the module must not drag in the Preact context it
+// needs, nor the editor bundle behind it.
+vi.mock("../../react/hooks.jsx", () => ({ useTriliumEvent: vi.fn(), useTriliumOption: () => [""] }));
+
+import type FNote from "../../../entities/fnote.js";
+import type LoadResults from "../../../services/load_results.js";
+import search from "../../../services/search.js";
+import { buildQuickActions, refreshQuickActions } from "./ai_quick_actions.js";
+
+interface NoteStub {
+ noteId: string;
+ title: string;
+ type: string;
+ isArchived: boolean;
+ isContentAvailable: () => boolean;
+ getContent: () => Promise<string | undefined>;
+ getIcon: () => string;
+}
+
+function makeNote(overrides: Partial<NoteStub> = {}): FNote {
+ return {
+ noteId: "act",
+ title: "Make it a haiku",
+ type: "text",
+ isArchived: false,
+ isContentAvailable: () => true,
+ getContent: async () => "<p>Rewrite this as a haiku.</p>",
+ getIcon: () => "bx bx-note",
+ ...overrides
+ } as unknown as FNote;
+}
+
+/** The custom group, or `undefined` when nothing earned one. */
+async function customGroup() {
+ return (await buildQuickActions()).find((group) => group.id === "custom");
+}
+
+function loadResults({ attributes = [], noteIds = [] }: {
+ attributes?: Array<{ type: string; name?: string; value?: string }>;
+ noteIds?: string[];
+}) {
+ return {
+ getAttributeRows: () => attributes,
+ getNoteIds: () => noteIds
+ } as unknown as LoadResults;
+}
+
+describe("custom AI quick actions", () => {
+ beforeEach(() => {
+ vi.mocked(search.searchForNotes).mockReset();
+ vi.stubGlobal("logError", vi.fn());
+ });
+
+ it("offers one action per labelled note, titled by it and prompted by its content", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([
+ makeNote(),
+ makeNote({ noteId: "second", title: "Draft a reply", type: "code", getContent: async () => " Draft a reply. " })
+ ]);
+
+ const group = await customGroup();
+ expect(group?.submenu).toBe(true);
+ expect(group?.actions).toEqual([
+ {
+ id: "custom:act",
+ label: "Make it a haiku",
+ prompt: "Rewrite this as a haiku.",
+ iconClass: "bx bx-note"
+ },
+ // A code note is already the plain text the model wants; only the padding goes.
+ expect.objectContaining({ id: "custom:second", prompt: "Draft a reply." })
+ ]);
+
+ expect(vi.mocked(search.searchForNotes)).toHaveBeenCalledWith("#aiQuickAction");
+ });
+
+ // The instruction is what the user wrote, not the markup they wrote it in — which would spend
+ // tokens on tags and invite the model to answer in kind.
+ it("reads a text note's prompt as plain text, keeping the breaks between its blocks", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([makeNote({
+ getContent: async () => "<h2>Summarize</h2><ul><li>One bullet per idea</li><li>Keep &amp; the wording</li></ul>"
+ })]);
+
+ expect((await customGroup())?.actions[0].prompt)
+ .toBe("Summarize\nOne bullet per idea\nKeep & the wording");
+ });
+
+ it("passes over the notes that cannot contribute a prompt", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([
+ makeNote({ noteId: "archived", isArchived: true }),
+ makeNote({ noteId: "protected", isContentAvailable: () => false }),
+ makeNote({ noteId: "image", type: "image" }),
+ // Written but not yet filled in: an action with no instruction would hand the selection
+ // to the model with nothing to do to it.
+ makeNote({ noteId: "empty", getContent: async () => "<p>&nbsp;</p>" })
+ ]);
+
+ expect(await customGroup()).toBeUndefined();
+ });
+
+ it("keeps the group out of the menu entirely when the search fails", async () => {
+ vi.mocked(search.searchForNotes).mockRejectedValue(new Error("offline"));
+
+ expect(await customGroup()).toBeUndefined();
+ expect(vi.mocked(globalThis.logError)).toHaveBeenCalled();
+ });
+
+ describe("refreshQuickActions", () => {
+ it("rebuilds when a note gains the label or is made from the template", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([]);
+ const setQuickActions = vi.fn();
+
+ await refreshQuickActions(loadResults({ attributes: [{ type: "label", name: "aiQuickAction" }] }), setQuickActions);
+ await refreshQuickActions(loadResults({ attributes: [{ type: "relation", value: "_template_ai_quick_action" }] }), setQuickActions);
+
+ expect(setQuickActions).toHaveBeenCalledTimes(2);
+ });
+
+ it("ignores a change to a label or a note that feeds nothing", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([]);
+ const setQuickActions = vi.fn();
+
+ await refreshQuickActions(loadResults({ attributes: [{ type: "label", name: "snippet" }] }), setQuickActions);
+ await refreshQuickActions(loadResults({ noteIds: ["someOtherNote"] }), setQuickActions);
+
+ expect(setQuickActions).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts
new file mode 100644
index 0000000000..4c405f7977
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts
@@ -0,0 +1,169 @@
+import type { AiQuickAction, AiQuickActionGroup } from "@triliumnext/ckeditor5";
+import { useEffect, useState } from "preact/hooks";
+
+import type FNote from "../../../entities/fnote.js";
+import debounce from "../../../services/debounce.js";
+import froca from "../../../services/froca.js";
+import { t } from "../../../services/i18n.js";
+import type LoadResults from "../../../services/load_results.js";
+import search from "../../../services/search.js";
+import { useTriliumEvent, useTriliumOption } from "../../react/hooks.jsx";
+import { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
+
+/**
+ * Everything the AI assistant's menu offers: the built-in groups, followed by the instructions the
+ * user wrote themselves.
+ *
+ * The built-ins are ready synchronously; the custom ones are notes and have to be searched for and
+ * read. So the assistant starts on the built-ins alone and is handed the full list once it arrives
+ * — the menu redraws itself (`AiAssistantUI.updateQuickActions`), which is the same reason the
+ * editor need not be rebuilt when a custom action is written or edited.
+ */
+export function useAiQuickActions(): AiQuickActionGroup[] {
+ const [ quickActions, setQuickActions ] = useState<AiQuickActionGroup[]>(buildAiAssistantQuickActions);
+ // The built-in Translate group lists these, so a change to them rebuilds the whole list.
+ const [ contentLanguages ] = useTriliumOption("languages");
+
+ useEffect(() => {
+ void buildQuickActions().then(setQuickActions);
+ }, [ contentLanguages ]);
+
+ useTriliumEvent("entitiesReloaded", async ({ loadResults }) => {
+ await refreshQuickActions(loadResults, setQuickActions);
+ });
+
+ return quickActions;
+}
+
+/** The label marking a note as an instruction to offer in the assistant's menu. */
+const LABEL = "aiQuickAction";
+/** The built-in template a user makes one of these notes from. */
+const TEMPLATE_NOTE_ID = "_template_ai_quick_action";
+const GROUP_ID = "custom";
+
+/** The note ids the last build drew on, so a change elsewhere can be ignored. */
+let actionNoteIds = new Set<string>();
+const debouncedRefreshIfAffected = debounce(refreshIfAffected, 1000);
+
+export async function buildQuickActions(): Promise<AiQuickActionGroup[]> {
+ const groups = buildAiAssistantQuickActions();
+ const actions = await getCustomQuickActions();
+
+ if (actions.length) {
+ groups.push({
+ id: GROUP_ID,
+ label: t("ai_assistant.group_custom"),
+ iconClass: "bx bx-user",
+ // A submenu, like the groups it follows: the user's own actions are named by them and
+ // there is no telling how many there will be, which is exactly the case the top level
+ // of the menu cannot absorb.
+ submenu: true,
+ actions
+ });
+ }
+
+ return groups;
+}
+
+/**
+ * The user's own instructions: one per `#aiQuickAction` note, titled by the note and worded by its
+ * content — the shape a text snippet has, for the same reason. A note is a better home for a prompt
+ * than a setting is: it can be written in the editor, revised, synced and organized like anything
+ * else.
+ */
+async function getCustomQuickActions(): Promise<AiQuickAction[]> {
+ try {
+ // Type is filtered here rather than in the query: a query starting with "(" trips the
+ // search lexer (see `snippets.ts`, which works around the same thing).
+ const notes = (await search.searchForNotes(`#${LABEL}`))
+ .filter((note) => (note.type === "text" || note.type === "code")
+ && !note.isArchived && note.isContentAvailable());
+
+ const actions: AiQuickAction[] = [];
+ actionNoteIds = new Set(notes.map((note) => note.noteId));
+
+ for (const note of notes) {
+ const prompt = await readPrompt(note);
+ // An empty note is one the user has not written yet, and an action with no instruction
+ // would send the selection to the model with nothing to do to it.
+ if (prompt) {
+ actions.push({
+ id: `${GROUP_ID}:${note.noteId}`,
+ label: note.title,
+ prompt,
+ iconClass: note.getIcon()
+ });
+ }
+ }
+
+ return actions;
+ } catch (e) {
+ logError("Error while building the custom AI quick actions: ", e);
+ return [];
+ }
+}
+
+/**
+ * What the note tells the model. A code note is already plain text; a text note's content is HTML,
+ * and the instruction is what the user wrote rather than the markup they wrote it in — sending the
+ * markup spends tokens on it and invites the model to answer in kind.
+ */
+async function readPrompt(note: FNote): Promise<string> {
+ const content = await note.getContent();
+ if (!content) {
+ return "";
+ }
+ if (note.type !== "text") {
+ return content.trim();
+ }
+
+ // The block boundaries carry a line break `textContent` would drop, gluing paragraphs together
+ // ("<p>a</p><p>b</p>" → "ab"). A prompt written as steps or a list depends on them.
+ const withBreaks = content.replace(
+ /<(?:br\b|\/(?:p|div|li|h[1-6]|blockquote|figcaption|pre|td|th|tr)\b)[^>]*>/gi,
+ "\n"
+ );
+ return (new DOMParser().parseFromString(withBreaks, "text/html").body.textContent ?? "")
+ .replace(/[^\S\n]+/g, " ")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+/**
+ * Rebuilds the list when something that feeds it changed: a note gaining or losing the label, one
+ * being made from the template, or the content or title of a note already in the list.
+ *
+ * Unlike a snippet, whose text reaches the editor through a getter, an action's prompt is baked
+ * into the definition — so a content edit means a rebuild, debounced so that typing a prompt does
+ * not rebuild once per keystroke.
+ */
+export async function refreshQuickActions(
+ loadResults: LoadResults,
+ setQuickActions: (value: AiQuickActionGroup[]) => void
+) {
+ const marksAnAction = loadResults.getAttributeRows().some((attr) => (attr.type === "label"
+ ? attr.name === LABEL
+ : attr.value === TEMPLATE_NOTE_ID));
+
+ if (marksAnAction) {
+ setQuickActions(await buildQuickActions());
+ return;
+ }
+
+ const affectedNoteIds = loadResults.getNoteIds();
+ if (affectedNoteIds.length) {
+ debouncedRefreshIfAffected(affectedNoteIds, setQuickActions);
+ }
+}
+
+async function refreshIfAffected(
+ affectedNoteIds: string[],
+ setQuickActions: (value: AiQuickActionGroup[]) => void
+) {
+ if (!affectedNoteIds.some((noteId) => actionNoteIds.has(noteId))) {
+ return;
+ }
+
+ await froca.getNotes(affectedNoteIds, true);
+ setQuickActions(await buildQuickActions());
+}
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 9b06f17ded..698f133055 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -440,6 +440,7 @@
"text-snippet": "Text Snippet",
"markdown-snippet": "Markdown Snippet",
"code-snippet": "Code Snippet",
+ "ai-quick-action": "AI Quick Action",
"description": "Description",
"list-view": "List View",
"grid-view": "Grid View",
diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.ts
index e1dc4032e7..bb95ee11b8 100644
--- a/packages/commons/src/lib/builtin_attributes.ts
+++ b/packages/commons/src/lib/builtin_attributes.ts
@@ -183,6 +183,8 @@ const BUILTIN_ATTRIBUTES = [
{ type: "label", name: "snippetDescription", valueType: "text", hasUserValue: true },
{ type: "label", name: "textSnippet", valueType: "boolean" },
{ type: "label", name: "textSnippetDescription", valueType: "text", hasUserValue: true },
+ // Offers the note's content as an instruction in the text editor's AI assistant menu.
+ { type: "label", name: "aiQuickAction", valueType: "boolean" },
// Forces the table of contents open or shut; without the label the heading count decides.
{ type: "label", name: "toc", valueType: "select", selectOptions: [ "show", "hide" ] },
{ type: "label", name: "color", valueType: "color" },
diff --git a/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts b/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts
index c62f1810de..3200e2245b 100644
--- a/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts
+++ b/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts
@@ -39,6 +39,7 @@ describe("buildHiddenSubtreeTemplates", () => {
"_template_text_snippet",
"_template_markdown_snippet",
"_template_code_snippet",
+ "_template_ai_quick_action",
"_template_list_view",
"_template_grid_view",
"_template_calendar",
diff --git a/packages/trilium-core/src/services/hidden_subtree_templates.ts b/packages/trilium-core/src/services/hidden_subtree_templates.ts
index 7a838fffb4..264d8684e4 100644
--- a/packages/trilium-core/src/services/hidden_subtree_templates.ts
+++ b/packages/trilium-core/src/services/hidden_subtree_templates.ts
@@ -78,6 +78,24 @@ export default function buildHiddenSubtreeTemplates() {
}
]
},
+ {
+ // A text note rather than a code one: the content is an instruction written in
+ // prose, and the editor is where the user already is when they think of it.
+ id: "_template_ai_quick_action",
+ type: "text",
+ title: t("hidden_subtree_templates.ai-quick-action"),
+ icon: "bx-bot",
+ attributes: [
+ {
+ name: "template",
+ type: "label"
+ },
+ {
+ name: "aiQuickAction",
+ type: "label"
+ }
+ ]
+ },
{
id: "_template_list_view",
type: "book",