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(llm): let the AI chat answer questions from the User Guide
Elian Doran8c91a108d558
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 6597c9477c..23aac9f7fe 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3176,7 +3176,9 @@"delete_note": "Delete note","move_note": "Move note","clone_note": "Clone note",- "search_icons": "Search icons"+ "search_icons": "Search icons",+ "search_help": "Search User Guide",+ "get_help_toc": "Get User Guide contents"}},"common": {diff --git a/apps/server/src/services/llm/providers/system_prompt.ts b/apps/server/src/services/llm/providers/system_prompt.tsindex 5702634f36..2cc138a115 100644--- a/apps/server/src/services/llm/providers/system_prompt.ts+++ b/apps/server/src/services/llm/providers/system_prompt.ts@@ -56,6 +56,9 @@ export function buildSystemPrompt(messages: LlmMessage[], config: LlmProviderConparts.push(`Never prepend emojis or other decorative characters to note titles. To give a note a visual marker, find a fitting icon with search_icons and assign it via set_attribute as the note's 'iconClass' label (e.g. value 'bx bx-rocket').`);+ parts.push(+ `For questions about how to use Trilium itself (features, settings, keyboard shortcuts, "how do I…?"), consult the built-in User Guide instead of relying on your own knowledge — it matches the installed version. Use search_help to find pages by keyword; if that misses, use get_help_toc to browse the table of contents (the guide may name a concept differently than the user, e.g. placing a note in two locations is "cloning"). Base your answer on those pages and link them with [[noteId]] so the user can open the full documentation.`+ );} else if (config.contextNoteId) {parts.push(`You can see the current note's metadata above, but you cannot search or access other notes. If the user asks about other notes, inform them that "Note access" is disabled and they need to enable it in the chat settings (click on the model name dropdown and toggle "Note access").`diff --git a/apps/server/src/services/llm/tools/help_tools.spec.ts b/apps/server/src/services/llm/tools/help_tools.spec.tsnew file mode 100644index 0000000000..e3a4e85c52--- /dev/null+++ b/apps/server/src/services/llm/tools/help_tools.spec.ts@@ -0,0 +1,149 @@+import { becca, becca_easy_mocking } from "@triliumnext/core";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { helpTools, resetHelpIndex } from "./help_tools.js";+import type { ToolDefinition } from "./tool_registry.js";++const { buildNote } = becca_easy_mocking;++/** Fake on-disk help pages: path suffix → HTML content. */+const docFiles = vi.hoisted(() => new Map<string, string>());++// Help pages are doc notes whose HTML lives on disk — serve them from the+// docFiles fixture map and pass every other path through to the real fs.+vi.mock("fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("fs")>();+ const readFileSync = ((filePath: unknown, ...rest: unknown[]) => {+ const pathStr = String(filePath);+ for (const [suffix, content] of docFiles) {+ if (pathStr.endsWith(suffix)) return content;+ }+ if (pathStr.includes("doc_notes")) {+ throw new Error(`ENOENT: ${pathStr}`);+ }+ return (actual.readFileSync as (...args: unknown[]) => unknown)(filePath, ...rest);+ }) as typeof actual.readFileSync;+ const mocked = { ...actual, readFileSync };+ return { ...mocked, default: mocked };+});++function getTool(name: string): ToolDefinition {+ for (const [n, def] of helpTools) {+ if (n === name) return def;+ }+ throw new Error(`Tool ${name} not registered`);+}++/** A miniature `_help` subtree: root → section → page. */+function buildHelpTree() {+ buildNote({+ id: "_help",+ title: "User Guide",+ children: [+ {+ id: "_help_basics",+ title: "Basic Concepts",+ children: [+ {+ id: "_help_notes",+ title: "Notes",+ children: [+ { id: "_help_cloning", title: "Cloning Notes", type: "doc", "#docName": "User Guide/User Guide/Cloning Notes" }+ ]+ }+ ]+ },+ { id: "_help_install", title: "Installation & Setup", type: "doc", "#docName": "User Guide/User Guide/Installation" }+ ]+ });+ docFiles.set("Cloning Notes.html", "<p>A note can be placed in multiple locations. Prefix & installation hints.</p>");+ docFiles.set("Installation.html", "<p>Download the desktop app.</p>");+}++interface SearchHelpResult {+ totalResults: number;+ results: { noteId: string; title: string; path: string; contentPreview: string | null }[];+}++describe("help_tools", () => {+ beforeEach(() => {+ becca.reset();+ resetHelpIndex();+ docFiles.clear();+ vi.clearAllMocks();+ });++ describe("search_help", () => {+ it("matches page bodies (which live on disk, invisible to regular search) and returns breadcrumb paths", () => {+ buildHelpTree();++ const result = getTool("search_help").execute({ query: "multiple locations" }) as SearchHelpResult;++ expect(result.totalResults).toBe(1);+ expect(result.results[0]).toMatchObject({+ noteId: "_help_cloning",+ title: "Cloning Notes",+ path: "Basic Concepts > Notes"+ });+ expect(result.results[0].contentPreview).toContain("multiple locations");+ });++ it("requires every query word (AND semantics)", () => {+ buildHelpTree();++ const result = getTool("search_help").execute({ query: "cloning fnordhotzenplotz" }) as SearchHelpResult;++ expect(result.totalResults).toBe(0);+ expect(result.results).toEqual([]);+ });++ it("ranks title matches above body matches and respects the limit", () => {+ buildHelpTree();+ // "installation" occurs in the Installation page title AND in the Cloning page body.++ const all = getTool("search_help").execute({ query: "installation" }) as SearchHelpResult;+ expect(all.totalResults).toBe(2);+ expect(all.results.map(r => r.noteId)).toEqual(["_help_install", "_help_cloning"]);++ const limited = getTool("search_help").execute({ query: "installation", limit: 1 }) as SearchHelpResult;+ expect(limited.totalResults).toBe(2);+ expect(limited.results).toHaveLength(1);+ });++ it("rejects an empty query", () => {+ buildHelpTree();+ expect(getTool("search_help").execute({ query: " " }))+ .toEqual({ error: "Empty search query." });+ });++ it("returns an error when the help subtree is absent or empty", () => {+ expect(getTool("search_help").execute({ query: "anything" }))+ .toEqual({ error: "The built-in User Guide is not available in this installation." });++ buildNote({ id: "_help", title: "User Guide" }); // present but not yet populated+ expect(getTool("search_help").execute({ query: "anything" }))+ .toEqual({ error: "The built-in User Guide is not available in this installation." });+ });+ });++ describe("get_help_toc", () => {+ it("returns an indented outline of every help page with its noteId", () => {+ buildHelpTree();++ const result = getTool("get_help_toc").execute({}) as { pageCount: number; toc: string };++ expect(result.pageCount).toBe(4);+ expect(result.toc.split("\n")).toEqual([+ "Basic Concepts (_help_basics)",+ " Notes (_help_notes)",+ " Cloning Notes (_help_cloning)",+ "Installation & Setup (_help_install)"+ ]);+ });++ it("returns an error when the help subtree is absent", () => {+ expect(getTool("get_help_toc").execute({}))+ .toEqual({ error: "The built-in User Guide is not available in this installation." });+ });+ });+});diff --git a/apps/server/src/services/llm/tools/help_tools.ts b/apps/server/src/services/llm/tools/help_tools.tsnew file mode 100644index 0000000000..ef5dd547b9--- /dev/null+++ b/apps/server/src/services/llm/tools/help_tools.ts@@ -0,0 +1,200 @@+/**+ * LLM tools for consulting Trilium's built-in User Guide (the in-app help+ * notes under the hidden `_help` subtree). These let the assistant answer+ * "how do I…?" questions about Trilium itself, grounded in the documentation+ * that ships with the running version instead of possibly stale training data.+ *+ * Help pages are `doc` notes: their HTML lives on disk rather than in the+ * database, so Trilium's regular search cannot see their bodies. search_help+ * therefore matches against a lazily built in-memory index of the page texts+ * (~1 MB for the whole guide, loaded once per process).+ */++import { becca, type BNote } from "@triliumnext/core";+import { z } from "zod";++import { getContentPreview, getDocNoteHtml } from "./helpers.js";+import { defineTools } from "./tool_registry.js";++const HELP_ROOT_NOTE_ID = "_help";+const DEFAULT_SEARCH_LIMIT = 10;+/** The User Guide is only a few levels deep; bound traversal defensively. */+const MAX_HELP_DEPTH = 10;+/** A word occurrence in the title outweighs one in the body. */+const TITLE_MATCH_WEIGHT = 10;++export const helpTools = defineTools({+ search_help: {+ description: [+ "Search Trilium's built-in User Guide — the documentation for Trilium itself.",+ "Use this to answer questions about how to use Trilium: features, settings, keyboard shortcuts, sync, scripting, themes, etc.",+ "Full-text keyword search over the help pages; keep queries to a few keywords (e.g. 'keyboard shortcuts', 'protected notes').",+ "If a query finds nothing, retry with synonyms or browse get_help_toc — the guide may name the concept differently (e.g. placing a note in two locations is 'cloning').",+ "Read a found page with get_note_content."+ ].join(" "),+ inputSchema: z.object({+ query: z.string().describe("Keyword search query (a few plain words, not a full question)"),+ limit: z.number().optional().describe("Maximum number of results to return. Defaults to 10.")+ }),+ execute: ({ query, limit = DEFAULT_SEARCH_LIMIT }) => {+ if (!isHelpAvailable()) {+ return { error: "The built-in User Guide is not available in this installation." };+ }++ const words = query.toLowerCase().split(/\s+/).filter(Boolean);+ if (words.length === 0) {+ return { error: "Empty search query." };+ }++ const matches = getHelpIndex()+ .map((page) => ({ page, score: scorePage(page, words) }))+ .filter((m) => m.score > 0)+ .sort((a, b) => b.score - a.score);++ const results = matches.slice(0, limit).map(({ page }) => {+ const note = becca.notes[page.noteId];+ if (!note) return null;+ return {+ noteId: page.noteId,+ title: note.getTitleOrProtected(),+ path: getHelpPath(note),+ contentPreview: getContentPreview(note)+ };+ }).filter(Boolean);++ return {+ totalResults: matches.length,+ results+ };+ }+ },++ get_help_toc: {+ description: [+ "Get the table of contents of Trilium's built-in User Guide: every help page's title and note ID, hierarchically indented.",+ "Use this when search_help does not find the right page (the guide may name the concept differently than the user), or to get an overview of a documentation area.",+ "Read a page with get_note_content."+ ].join(" "),+ inputSchema: z.object({}),+ execute: () => {+ if (!isHelpAvailable()) {+ return { error: "The built-in User Guide is not available in this installation." };+ }++ const helpRoot = becca.getNoteOrThrow(HELP_ROOT_NOTE_ID);+ const lines: string[] = [];+ collectTocLines(helpRoot, 0, lines);++ return {+ pageCount: lines.length,+ toc: lines.join("\n")+ };+ }+ }+});++/** One help page in the search index; title and text are lowercased for matching. */+interface HelpPageIndexEntry {+ noteId: string;+ titleLower: string;+ textLower: string;+}++/**+ * Lazily built index of all help pages. The guide only changes on upgrade+ * (which restarts the server), so it is cached for the process lifetime.+ */+let helpIndex: HelpPageIndexEntry[] | null = null;++/** Drop the cached search index (for tests). */+export function resetHelpIndex(): void {+ helpIndex = null;+}++function getHelpIndex(): HelpPageIndexEntry[] {+ if (helpIndex === null) {+ helpIndex = [];+ collectIndexEntries(becca.getNoteOrThrow(HELP_ROOT_NOTE_ID), 0, helpIndex);+ }+ return helpIndex;+}++function collectIndexEntries(note: BNote, depth: number, entries: HelpPageIndexEntry[]): void {+ if (depth >= MAX_HELP_DEPTH) {+ return;+ }+ for (const child of note.getChildNotes()) {+ entries.push({+ noteId: child.noteId,+ titleLower: child.getTitleOrProtected().toLowerCase(),+ textLower: htmlToPlainText(getDocNoteHtml(child) ?? "").toLowerCase()+ });+ collectIndexEntries(child, depth + 1, entries);+ }+}++/**+ * Score a page against the query words: every word must occur in the title or+ * body (AND semantics), title occurrences weigh more than body occurrences.+ * Returns 0 when any word is missing.+ */+function scorePage(page: HelpPageIndexEntry, words: string[]): number {+ let score = 0;+ for (const word of words) {+ const titleHits = countOccurrences(page.titleLower, word);+ const bodyHits = countOccurrences(page.textLower, word);+ if (titleHits + bodyHits === 0) {+ return 0;+ }+ score += titleHits * TITLE_MATCH_WEIGHT + bodyHits;+ }+ return score;+}++function countOccurrences(haystack: string, needle: string): number {+ return haystack.split(needle).length - 1;+}++/** Crude tag stripping — good enough for keyword matching, not for display. */+function htmlToPlainText(html: string): string {+ return html+ .replace(/<[^>]+>/g, " ")+ .replace(/ /g, " ")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, "\"")+ .replace(/'/g, "'")+ .replace(/&/g, "&")+ .replace(/\s+/g, " ");+}++/** The help subtree exists only once the in-app help has been imported. */+function isHelpAvailable(): boolean {+ const helpRoot = becca.getNote(HELP_ROOT_NOTE_ID);+ return !!helpRoot && helpRoot.getChildNotes().length > 0;+}++/**+ * Breadcrumb of ancestor titles within the User Guide (excluding the help+ * root and the page itself), e.g. "Basic Concepts > Notes".+ */+function getHelpPath(note: BNote): string {+ const titles: string[] = [];+ let current: BNote | undefined = note.getParentNotes()[0];+ for (let depth = 0; depth < MAX_HELP_DEPTH && current && current.noteId !== HELP_ROOT_NOTE_ID; depth++) {+ titles.unshift(current.getTitleOrProtected());+ current = current.getParentNotes()[0];+ }+ return titles.join(" > ");+}++/** Append one indented `Title (noteId)` line per help page, depth-first. */+function collectTocLines(note: BNote, depth: number, lines: string[]): void {+ if (depth >= MAX_HELP_DEPTH) {+ return;+ }+ for (const child of note.getChildNotes()) {+ lines.push(`${" ".repeat(depth)}${child.getTitleOrProtected()} (${child.noteId})`);+ collectTocLines(child, depth + 1, lines);+ }+}diff --git a/apps/server/src/services/llm/tools/helpers.spec.ts b/apps/server/src/services/llm/tools/helpers.spec.tsindex cf13bfa0ba..fb8ecf796b 100644--- a/apps/server/src/services/llm/tools/helpers.spec.ts+++ b/apps/server/src/services/llm/tools/helpers.spec.ts@@ -14,11 +14,33 @@ vi.mock("@triliumnext/core", async (importOriginal) => {};});+/** Fake on-disk help pages for getDocNoteHtml: path suffix → HTML content. */+const docFiles = vi.hoisted(() => new Map<string, string>());++// Doc notes read their HTML from disk — serve them from the docFiles fixture+// map and pass every other path through to the real fs.+vi.mock("fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("fs")>();+ const readFileSync = ((filePath: unknown, ...rest: unknown[]) => {+ const pathStr = String(filePath);+ for (const [suffix, content] of docFiles) {+ if (pathStr.endsWith(suffix)) return content;+ }+ if (pathStr.includes("doc_notes")) {+ throw new Error(`ENOENT: ${pathStr}`);+ }+ return (actual.readFileSync as (...args: unknown[]) => unknown)(filePath, ...rest);+ }) as typeof actual.readFileSync;+ const mocked = { ...actual, readFileSync };+ return { ...mocked, default: mocked };+});+import {applyTextEdits,flag,getAttachmentContentPreview,getContentPreview,+ getDocNoteHtml,getNoteContentForLlm,getNoteMeta,setNoteContentFromLlm@@ -42,11 +64,22 @@ function noteStub(overrides: Partial<Record<string, unknown>> = {}): BNote {getParentNotes: () => [],getAttributes: () => [],getAttachments: () => [],+ getLabelValue: () => null,setContent: vi.fn(),...overrides} as unknown as BNote;}+/** A doc-note stub (in-app help page) with the given #docName label. */+function docNoteStub(docName: string | null) {+ return noteStub({+ type: "doc",+ blobId: "",+ getContent: () => "",+ getLabelValue: (name: string) => (name === "docName" ? docName : null)+ });+}+function attachmentStub(overrides: Partial<Record<string, unknown>> = {}): BAttachment {return {attachmentId: "a1",@@ -98,6 +131,39 @@ describe("getNoteContentForLlm", () => {});});+describe("getDocNoteHtml / doc notes", () => {+ beforeEach(() => docFiles.clear());++ it("reads the page HTML from disk under doc_notes/en", () => {+ docFiles.set("Cloning Notes.html", "<h2>Cloning</h2>");+ expect(getDocNoteHtml(docNoteStub("User Guide/User Guide/Cloning Notes"))).toBe("<h2>Cloning</h2>");+ });++ it("returns null without a docName label, on a missing file, and on path traversal attempts", () => {+ expect(getDocNoteHtml(docNoteStub(null))).toBeNull();+ expect(getDocNoteHtml(docNoteStub("User Guide/Nonexistent Page"))).toBeNull();+ // Traversal attempts must be rejected before touching the filesystem —+ // register a catch-all fixture so any read would be visible.+ docFiles.set(".html", "<p>leaked</p>");+ expect(getDocNoteHtml(docNoteStub("../../../../etc/passwd"))).toBeNull();+ expect(getDocNoteHtml(docNoteStub("/etc/passwd"))).toBeNull();+ });++ it("getNoteContentForLlm converts doc-note HTML to Markdown", () => {+ docFiles.set("Cloning Notes.html", "<h2>Cloning</h2><p>Place a note in two locations.</p>");+ const content = getNoteContentForLlm(docNoteStub("User Guide/User Guide/Cloning Notes"));+ expect(content).toContain("## Cloning");+ expect(content).toContain("Place a note in two locations.");+ });++ it("getNoteContentForLlm and getContentPreview degrade gracefully for unresolvable doc notes", () => {+ getBlobMock.mockReturnValue(null);+ const note = docNoteStub(null);+ expect(getNoteContentForLlm(note)).toBe("[doc content not available]");+ expect(getContentPreview(note)).toBeNull();+ });+});+describe("setNoteContentFromLlm", () => {it("renders Markdown to HTML for text notes", () => {const note = noteStub({ type: "text" });diff --git a/apps/server/src/services/llm/tools/helpers.ts b/apps/server/src/services/llm/tools/helpers.tsindex 339b298055..43ca1bff9f 100644--- a/apps/server/src/services/llm/tools/helpers.ts+++ b/apps/server/src/services/llm/tools/helpers.ts@@ -2,10 +2,12 @@* Shared helpers for LLM tools — content conversion, metadata building, and previews.*/-import { type BAttachment, type BNote, markdownExportService as markdownExport,markdownImportService as markdownImport } from "@triliumnext/core";+import { type BAttachment, becca, type BNote, markdownExportService as markdownExport, markdownImportService as markdownImport } from "@triliumnext/core";import { unwrapStringOrBuffer } from "@triliumnext/core/src/services/utils/binary.js";+import { readFileSync } from "fs";+import path from "path";-import { becca } from "@triliumnext/core";+import resourceDir from "../../resource_dir.js";const CONTENT_PREVIEW_MAX_LENGTH = 500;const ATTACHMENT_PREVIEW_MAX_LENGTH = 200;@@ -30,6 +32,13 @@ export function flag(value: boolean | undefined): true | undefined {* Text notes are converted from HTML to Markdown to reduce token usage.*/export function getNoteContentForLlm(note: BNote) {+ if (note.type === "doc") {+ // Doc notes (in-app help / User Guide pages) store no content in the+ // database — their HTML lives on disk and is fetched by the client.+ const html = getDocNoteHtml(note);+ return html ? markdownExport.toMarkdown(html) : "[doc content not available]";+ }+const content = note.getContent();if (typeof content !== "string") {// For binary content (images, files), use extracted text if available.@@ -45,6 +54,32 @@ export function getNoteContentForLlm(note: BNote) {return content;}+/**+ * Resolve the on-disk HTML of a `doc` note (in-app help / User Guide pages,+ * identified by their `#docName` label), or null if it cannot be resolved.+ * The User Guide ships in English only, so the `en` tree is always used+ * (mirroring the client's doc_renderer behaviour).+ */+export function getDocNoteHtml(note: BNote): string | null {+ const docName = note.getLabelValue("docName");+ if (!docName) {+ return null;+ }++ const docNotesDir = path.resolve(resourceDir.RESOURCE_DIR, "doc_notes");+ const filePath = path.resolve(docNotesDir, "en", `${docName}.html`);+ if (!filePath.startsWith(docNotesDir + path.sep)) {+ // Path traversal guard — the docName label is note data, not trusted input.+ return null;+ }++ try {+ return readFileSync(filePath, "utf-8");+ } catch {+ return null;+ }+}+/*** Convert LLM-provided content to a format suitable for storage.* For text notes, converts Markdown to HTML.@@ -128,7 +163,7 @@ export function getContentPreview(note: BNote): string | null {}const full = getNoteContentForLlm(note);- if (!full || full === "[binary content]") {+ if (!full || full === "[binary content]" || full === "[doc content not available]") {return null;}diff --git a/apps/server/src/services/llm/tools/index.ts b/apps/server/src/services/llm/tools/index.tsindex 2ef3a54849..2c0f6001e6 100644--- a/apps/server/src/services/llm/tools/index.ts+++ b/apps/server/src/services/llm/tools/index.ts@@ -3,21 +3,23 @@* These reuse the same logic as ETAPI without any HTTP overhead.*/-export { noteTools } from "./note_tools.js";-export { attributeTools } from "./attribute_tools.js";+export { skillTools } from "../skills/index.js";export { attachmentTools } from "./attachment_tools.js";+export { attributeTools } from "./attribute_tools.js";+export { helpTools } from "./help_tools.js";export { hierarchyTools } from "./hierarchy_tools.js";export { iconTools } from "./icon_tools.js";-export { skillTools } from "../skills/index.js";+export { noteTools } from "./note_tools.js";export type { ToolDefinition } from "./tool_registry.js";export { ToolRegistry } from "./tool_registry.js";-import { noteTools } from "./note_tools.js";-import { attributeTools } from "./attribute_tools.js";+import { skillTools } from "../skills/index.js";import { attachmentTools } from "./attachment_tools.js";+import { attributeTools } from "./attribute_tools.js";+import { helpTools } from "./help_tools.js";import { hierarchyTools } from "./hierarchy_tools.js";import { iconTools } from "./icon_tools.js";-import { skillTools } from "../skills/index.js";+import { noteTools } from "./note_tools.js";import type { ToolRegistry } from "./tool_registry.js";/** All tool registries, for consumers that need to iterate every tool (e.g. MCP). */@@ -26,6 +28,7 @@ export const allToolRegistries: ToolRegistry[] = [attributeTools,attachmentTools,hierarchyTools,+ helpTools,iconTools,skillTools];