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
refactor(help): drop what only the User Guide's doc notes needed
Elian Doranb9e4f8b62d7d
diff --git a/.gitattributes b/.gitattributesindex 508388aa38..54d36d835c 100644--- a/.gitattributes+++ b/.gitattributes@@ -1,10 +1,8 @@# Mark files as auto-generated to simplify reviews.package-lock.json linguist-generated=true**/package-lock.json linguist-generated=true-apps/server/src/assets/doc_notes/en/User[[:space:]]Guide/** linguist-generated# Ignore from GitHub language stats.-apps/server/src/assets/doc_notes/en/User[[:space:]]Guide/**/*.html eol=lfapps/server/src/assets/doc_notes/** linguist-vendored=trueapps/edit-docs/demo/** linguist-vendored=truedocs/** linguist-vendored=truediff --git a/apps/client/src/services/doc_renderer.spec.ts b/apps/client/src/services/doc_renderer.spec.tsindex a90dc73b77..aaeb68357d 100644--- a/apps/client/src/services/doc_renderer.spec.ts+++ b/apps/client/src/services/doc_renderer.spec.ts@@ -37,25 +37,22 @@ function stubLoad(handler: (url: string, $el: JQuery<HTMLElement>) => { status?:}describe("isValidDocName", () => {- it("accepts valid docNames", () => {+ // Every docName in use comes from the hidden subtree definition and names one file directly+ // under doc_notes/<language>/.+ it("accepts the slugs the hidden subtree uses", () => {expect(isValidDocName("launchbar_intro")).toBe(true);- expect(isValidDocName("User Guide/Quick Start")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Quick Start")).toBe(true);- expect(isValidDocName("Quick Start Guide")).toBe(true);- expect(isValidDocName("quick_start_guide")).toBe(true);+ expect(isValidDocName("task_states")).toBe(true);+ expect(isValidDocName("share")).toBe(true);expect(isValidDocName("quick-start-guide")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Advanced Usage/Text Extraction (OCR)")).toBe(true);- expect(isValidDocName("User Guide/Basic Concepts and Features/Import & Export/Microsoft OneNote")).toBe(true);+ expect(isValidDocName("v2")).toBe(true);});- // A docName is a path built out of page titles, so it carries whatever punctuation the titles do.- // These are all real pages of the user guide.- it("accepts the punctuation real page titles carry", () => {- expect(isValidDocName("User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map)")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Advanced Usage/Configuration (config.ini or environment variables)")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Installation & Setup/Server Installation/1. Installing the server/Using Docker")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Scripting/Script API/Day.js")).toBe(true);- expect(isValidDocName("User Guide/User Guide/Scripting/Breaking changes/v0.103.0 `cheerio` is now deprecated")).toBe(true);+ it("rejects anything carrying a separator, so no path can be spelled at all", () => {+ expect(isValidDocName("User Guide/Quick Start")).toBe(false);+ expect(isValidDocName("Quick Start Guide")).toBe(false);+ expect(isValidDocName("Day.js")).toBe(false);+ expect(isValidDocName("Import & Export")).toBe(false);+ expect(isValidDocName("")).toBe(false);});it("rejects path traversal attacks", () => {@@ -65,12 +62,9 @@ describe("isValidDocName", () => {expect(isValidDocName("../../../../api/notes/_malicious/open")).toBe(false);expect(isValidDocName("..\\etc\\passwd")).toBe(false);expect(isValidDocName("foo\\bar")).toBe(false);- // Dots are allowed within a segment (see above), so a segment made of nothing else — which is- // what climbs out of the doc directory — has to be turned away in its own right.expect(isValidDocName("...")).toBe(false);expect(isValidDocName("foo/..")).toBe(false);expect(isValidDocName("foo/./bar")).toBe(false);- expect(isValidDocName("Day.js/../../etc/passwd")).toBe(false);});it("rejects URL manipulation attacks", () => {@@ -109,41 +103,21 @@ describe("renderDoc", () => {expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Invalid docName"));});- it("loads the localized doc, rewrites relative image src, and runs post-processing", async () => {+ it("loads the localized doc and runs post-processing", async () => {mockedLanguage = "de";const loadSpy = stubLoad((_url, $el) => {- $el.html(`<img src="pic.png"><a class="reference-link">x</a>`);+ $el.html(`<a class="reference-link">x</a>`);});- const $content = await renderDoc(fakeNote("Quick Start"));+ const $content = await renderDoc(fakeNote("launchbar_intro"));- // URL is base/doc_notes/<lang>/<docName with %20>.html- expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/de/Quick%20Start.html");- // The relative image src is rewritten to be prefixed with the doc directory.- expect($content.find("img").attr("src")).toBe("assets/doc_notes/de/pic.png");+ // URL is base/doc_notes/<lang>/<docName>.html+ expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/de/launchbar_intro.html");+ expect($content.find(".reference-link").length).toBe(1);expect(formatCodeBlocksMock).toHaveBeenCalledTimes(1);expect(applyReferenceLinksMock).toHaveBeenCalledTimes(1);});- it("forces English for User Guide docs regardless of the current language", async () => {- mockedLanguage = "fr";- const loadSpy = stubLoad(() => {});- await renderDoc(fakeNote("User Guide/Quick Start"));- expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/en/User%20Guide/Quick%20Start.html");- });-- it("percent-encodes ampersands in the docName (e.g. \"Import & Export\")", async () => {- const loadSpy = stubLoad(() => {});- await renderDoc(fakeNote("User Guide/Basic Concepts and Features/Import & Export/Microsoft OneNote"));- expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/en/User%20Guide/Basic%20Concepts%20and%20Features/Import%20%26%20Export/Microsoft%20OneNote.html");- });-- it("leaves the rest of a title's punctuation to the browser's own URL encoding", async () => {- const loadSpy = stubLoad(() => {});- await renderDoc(fakeNote("User Guide/User Guide/Advanced Usage/Note Map (Link map, Tree map)"));- expect(loadSpy.mock.calls[0][0]).toBe("assets/doc_notes/en/User%20Guide/User%20Guide/Advanced%20Usage/Note%20Map%20(Link%20map,%20Tree%20map).html");- });-it("falls back to the English doc when the localized load errors", async () => {mockedLanguage = "de";const requested: string[] = [];@@ -153,11 +127,11 @@ describe("renderDoc", () => {return url.includes("/de/") ? { status: "error" } : {};});- const $content = await renderDoc(fakeNote("Quick Start"));+ const $content = await renderDoc(fakeNote("launchbar_intro"));expect(requested).toEqual([- "assets/doc_notes/de/Quick%20Start.html",- "assets/doc_notes/en/Quick%20Start.html"+ "assets/doc_notes/de/launchbar_intro.html",+ "assets/doc_notes/en/launchbar_intro.html"]);expect($content.length).toBe(1);expect(loadSpy).toHaveBeenCalledTimes(2);@@ -169,14 +143,15 @@ describe("renderDoc", () => {it("uses the server-assets base path in standalone mode", async () => {(window as any).glob = { isStandalone: true, isDev: false, assetPath: "assets" };const loadSpy = stubLoad(() => {});- await renderDoc(fakeNote("Quick Start"));- expect(loadSpy.mock.calls[0][0]).toBe("server-assets/doc_notes/en/Quick%20Start.html");+ await renderDoc(fakeNote("launchbar_intro"));+ expect(loadSpy.mock.calls[0][0]).toBe("server-assets/doc_notes/en/launchbar_intro.html");});+ // In dev the asset path carries a `/src` suffix that the doc notes are not served under.it("uses the parent of assetPath in dev mode", async () => {- (window as any).glob = { isStandalone: false, isDev: true, assetPath: "assets" };+ (window as any).glob = { isStandalone: false, isDev: true, assetPath: "assets/src" };const loadSpy = stubLoad(() => {});- await renderDoc(fakeNote("Quick Start"));- expect(loadSpy.mock.calls[0][0]).toBe("assets/../doc_notes/en/Quick%20Start.html");+ await renderDoc(fakeNote("launchbar_intro"));+ expect(loadSpy.mock.calls[0][0]).toBe("assets/src/../doc_notes/en/launchbar_intro.html");});});diff --git a/apps/client/src/services/doc_renderer.ts b/apps/client/src/services/doc_renderer.tsindex 4c63a2d40a..cce861d2dd 100644--- a/apps/client/src/services/doc_renderer.ts+++ b/apps/client/src/services/doc_renderer.ts@@ -5,21 +5,13 @@ import { formatCodeBlocks } from "./syntax_highlight.js";/*** Validates a docName to prevent path traversal attacks.- * Allows forward slashes for subdirectories (e.g., "User Guide/Quick Start")- * but blocks traversal sequences and URL manipulation characters.+ *+ * A docName names one file directly under `doc_notes/<language>/`, so it is a plain slug with no+ * separators of any kind. The label is note data rather than trusted input, so anything else is+ * turned away instead of being reached for on disk.*/export function isValidDocName(docName: string): boolean {- // A docName is a path built out of page titles, so it has to carry the punctuation titles do:- // dots ("Day.js", "1. Installing the server", "v0.103.0 ..."), commas ("Note Map (Link map, Tree- // map)") and backticks ("`cheerio` is now deprecated"), on top of spaces, underscores, hyphens,- // ampersands, brackets and the slashes that separate the segments.- const validDocNameRegex = /^[a-zA-Z0-9_/\- ()&.,`]+$/;- if (!validDocNameRegex.test(docName)) return false;-- // Dots being allowed above, the traversal they would spell has to be turned away in its own- // right: a segment of nothing but dots is the one that climbs out of the doc directory, and no- // page title is ever that.- return !docName.split("/").some((segment) => /^\.+$/.test(segment));+ return /^[a-zA-Z0-9_-]+$/.test(docName);}export default function renderDoc(note: FNote) {@@ -39,7 +31,7 @@ export default function renderDoc(note: FNote) {/* v8 ignore next 8 -- the else branch is unreachable: fallbackUrl only differs from the primary url by language, so if the primary url was valid (we got here from a successful .load call) the "en" fallback url is valid too and never null */if (fallbackUrl) {$content.load(fallbackUrl, async () => {- await processContent(fallbackUrl, $content);+ await processContent($content);resolve($content);});} else {@@ -48,7 +40,7 @@ export default function renderDoc(note: FNote) {return;}- await processContent(url, $content);+ await processContent($content);resolve($content);});} else {@@ -57,15 +49,7 @@ export default function renderDoc(note: FNote) {});}-async function processContent(url: string, $content: JQuery<HTMLElement>) {- const dir = url.substring(0, url.lastIndexOf("/"));-- // Images are relative to the docnote but that will not work when rendered in the application since the path breaks.- $content.find("img").each((_i, el) => {- const $img = $(el);- $img.attr("src", `${dir}/${$img.attr("src")}`);- });-+async function processContent($content: JQuery<HTMLElement>) {formatCodeBlocks($content);// Apply reference links.@@ -80,12 +64,6 @@ function getUrl(docNameValue: string | null, language: string) {return null;}- // Cannot have spaces in the URL due to how JQuery.load works.- docNameValue = docNameValue.replaceAll(" ", "%20");- // Percent-encode ampersands (e.g. in "Import & Export") so they aren't misread when fetching the doc.- docNameValue = docNameValue.replaceAll("&", "%26");- // The user guide is available only in English, so make sure we are requesting correctly since 404s in standalone client are treated differently.- if (docNameValue.includes("User%20Guide")) language = "en";return `${getBasePath()}/doc_notes/${language}/${docNameValue}.html`;}diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsxindex 08fcc49bbe..e17b258e1d 100644--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx@@ -245,7 +245,7 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent):},{el: <TableOfContents />,- enabled: (noteType === "text" || noteType === "doc" || isPdf || noteType === "llmChat" || !!note?.isMarkdown()),+ enabled: (noteType === "text" || isPdf || noteType === "llmChat" || !!note?.isMarkdown()),tab: "outline"},{diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsxindex bc15368bf7..9578f1955e 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx@@ -36,7 +36,7 @@ export default function TableOfContents() {return (<RightPanelWidget id="toc" title={t("toc.table_of_contents")} grow>- {((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}+ {noteType === "text" && isReadOnly && <ReadOnlyTextTableOfContents />}{noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}{noteType === "file" && noteMime === "application/pdf" && <ContextDataTableOfContents />}{noteType === "llmChat" && <ContextDataTableOfContents />}diff --git a/apps/client/src/widgets/toc.ts b/apps/client/src/widgets/toc.tsindex 15358135aa..1975718ad7 100644--- a/apps/client/src/widgets/toc.ts+++ b/apps/client/src/widgets/toc.ts@@ -184,11 +184,7 @@ export default class TocWidget extends RightPanelWidget {return false;}- const isHelpNote = this.note.type === "doc" && this.note.noteId.startsWith("_help");- const isTextNote = this.note.type === "text";- const isNoteSupported = isTextNote || isHelpNote;-- return isNoteSupported+ return this.note.type === "text"&& !this.noteContext?.viewScope?.tocTemporarilyHidden&& this.noteContext?.viewScope?.viewMode === "default";}@@ -214,33 +210,10 @@ export default class TocWidget extends RightPanelWidget {return;}- // Check for type text unconditionally in case alwaysShowWidget is set- if (this.note.type === "text") {- const blob = await note.getBlob();- if (blob) {- const toc = await this.getToc(blob.content);- this.#updateToc(toc);- }- return;- }-- if (this.note.type === "doc") {- /**- * For document note types, we obtain the content directly from the DOM since it allows us to obtain processed data without- * requesting data twice. However, when immediately navigating to a new note the new document is not yet attached to the hierarchy,- * resulting in an empty TOC. The fix is to simply wait for it to pop up.- * TODO: Use a better method that is not prone to unnecessary delays and race conditions.- */- setTimeout(async () => {- const $contentEl = await this.noteContext?.getContentElement();- if ($contentEl) {- const content = $contentEl.html();- const toc = await this.getToc(content);- this.#updateToc(toc);- } else {- console.warn("Unable to get content element for doctype");- }- }, 250);+ const blob = await note.getBlob();+ if (blob) {+ const toc = await this.getToc(blob.content);+ this.#updateToc(toc);}}@@ -412,11 +385,10 @@ export default class TocWidget extends RightPanelWidget {// intervening events, do the readonly calculation at navigation// time and not at outline creation time// See https://github.com/zadam/trilium/issues/2828- const isDocNote = this.note.type === "doc";const isReadOnly = await this.noteContext.isReadOnly();let $container: JQuery<HTMLElement> | null = null;- if (isReadOnly || isDocNote) {+ if (isReadOnly) {$container = await this.noteContext.getContentElement();} else {const textEditor = await this.noteContext.getTextEditor();diff --git a/apps/client/src/widgets/type_widgets/Doc.css b/apps/client/src/widgets/type_widgets/Doc.cssindex 3dc440bcfa..0c48a95b9b 100644--- a/apps/client/src/widgets/type_widgets/Doc.css+++ b/apps/client/src/widgets/type_widgets/Doc.css@@ -35,17 +35,4 @@z-index: 50;margin: 0;padding-bottom: 0.25em;-}--img {- max-width: 100%;- height: auto;-}--td img {- max-width: 40vw;-}--figure.table {- overflow: auto !important;}\ No newline at end of filediff --git a/apps/server/src/services/llm/tools/doc_notes.ts b/apps/server/src/services/llm/tools/doc_notes.tsindex 6c1924ed95..9de8602686 100644--- a/apps/server/src/services/llm/tools/doc_notes.ts+++ b/apps/server/src/services/llm/tools/doc_notes.ts@@ -1,9 +1,9 @@/**- * Filesystem-backed resolution of in-app help pages, for the help tools.+ * Filesystem-backed resolution of `doc` notes, for the LLM tools.** Kept out of `@triliumnext/core`'s LLM code because it is the one tool helper- * that reads from `RESOURCE_DIR`: the User Guide ships as static HTML on disk,- * which the browser-hosted (standalone) build has no way to read synchronously.+ * that reads from `RESOURCE_DIR`: these pages ship as static HTML on disk, which+ * the browser-hosted (standalone) build has no way to read synchronously.*/import type { BNote } from "@triliumnext/core";@@ -13,10 +13,10 @@ import path from "path";import resourceDir from "../../resource_dir.js";/**- * 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).+ * Resolve the on-disk HTML of a `doc` note (identified by its `#docName` label),+ * or null if it cannot be resolved. The `en` tree is always used: the assistant+ * reads these pages to answer in its own words, so a translation would only+ * narrow what it can match against.*/export function getDocNoteHtml(note: BNote): string | null {const docName = note.getLabelValue("docName");diff --git a/docs/Developer Guide/Developer Guide/Documentation.md b/docs/Developer Guide/Developer Guide/Documentation.mdindex 9ca93656c0..64d2e04a23 100644--- a/docs/Developer Guide/Developer Guide/Documentation.md+++ b/docs/Developer Guide/Developer Guide/Documentation.md@@ -14,7 +14,7 @@ All documentation is stored in the [Trilium](https://github.com/TriliumNext/Tril* `docs/Release Notes` is also stored in Markdown format and can be freely edited.* The _Script API_ is auto-generated and is **not** committed to the repository. It is built into the gitignored `site/` directory and published to [docs.triliumnotes.org](https://docs.triliumnotes.org/); see [Updating the Script API](#updating-the-script-api) below.* `docs/User Guide` contains also Markdown-only documentation but must generally not be edited externally.- * The reason is that the `pnpm edit-docs:edit-docs` feature will not only import/export this documentation, but also generate the corresponding HTML documentation and meta structure in `src/public/app/doc_notes/en/User Guide`.+ * The reason is that the `pnpm edit-docs:edit-docs` feature will not only import/export this documentation, but also generate the note tree and the rendered page content that the in-app help is built from, in `apps/server/src/assets/help`.* It's theoretically possible to edit the Markdown files externally and then run `docs:edit` and trigger a change in order to build the documentation, but that would not be a very productive workflow.## Editing the documentationdiff --git a/packages/trilium-core/src/services/llm/tools/help_tools.ts b/packages/trilium-core/src/services/llm/tools/help_tools.tsindex ca4acb1d2d..e869fc964f 100644--- a/packages/trilium-core/src/services/llm/tools/help_tools.ts+++ b/packages/trilium-core/src/services/llm/tools/help_tools.ts@@ -4,17 +4,17 @@* "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).+ * Help pages are virtual notes, so the regular search reaches their bodies too.+ * search_help stays separate for the ranking it does: it is scoped to the guide+ * and weighs a title match above a body one, over a lazily built in-memory index+ * of the page texts (~1 MB for the whole guide, built once per process).*/import { z } from "zod";import becca from "../../../becca/becca.js";import type BNote from "../../../becca/entities/bnote.js";-import { getContentPreview, getDocNoteHtml } from "./helpers.js";+import { getContentPreview } from "./helpers.js";import { defineTools } from "./tool_registry.js";const HELP_ROOT_NOTE_ID = "_help";@@ -140,15 +140,8 @@ function collectIndexEntries(note: BNote, depth: number, entries: HelpPageIndexE}}-/**- * The text of a help page. Pages carry their content like any other note; `doc` notes elsewhere in- * the hidden subtree still keep theirs on disk, so those fall back to the host's reader.- */+/** The text of a help page, which carries its content like any other note. */function getPageText(note: BNote): string {- if (note.type === "doc") {- return htmlToPlainText(getDocNoteHtml(note) ?? "");- }-const content = note.getContent();if (typeof content !== "string") {diff --git a/packages/trilium-core/src/services/llm/tools/helpers.ts b/packages/trilium-core/src/services/llm/tools/helpers.tsindex 5bc1fb3bb6..c787780e06 100644--- a/packages/trilium-core/src/services/llm/tools/helpers.ts+++ b/packages/trilium-core/src/services/llm/tools/helpers.ts@@ -21,12 +21,13 @@ export const PROTECTED_SYSTEM_NOTES = new Set(["root", "_hidden", "_share", "_lblet docNoteHtmlReader: ((note: BNote) => string | null) | null = null;/**- * Register the host's reader for in-app help pages.+ * Register the host's reader for doc-note HTML.*- * `doc` notes (the User Guide) keep no content in the database — their HTML- * ships as static files, which the server reads off disk. The browser-hosted- * build has no synchronous way to do that, so hosts that can supply it register- * a reader here and the rest simply report the content as unavailable.+ * `doc` notes — the explanatory pages of the hidden subtree, such as the launcher+ * bar's — keep no content in the database: their HTML ships as static files, which+ * the server reads off disk. The browser-hosted build has no synchronous way to do+ * that, so hosts that can supply it register a reader here and the rest simply+ * report the content as unavailable.*/export function registerDocNoteHtmlReader(reader: (note: BNote) => string | null) {docNoteHtmlReader = reader;@@ -56,8 +57,8 @@ export function flag(value: boolean | undefined): true | undefined {*/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.+ // Doc notes 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]";}