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): render markdown in llmChat backlink excerpts
Elian Doran8dcaacdc5bfb
diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.tsindex 139411debb..1e29bb16fa 100644--- a/packages/trilium-core/src/routes/api/note_map.ts+++ b/packages/trilium-core/src/routes/api/note_map.ts@@ -3,9 +3,8 @@ import BNote from "../../becca/entities/bnote";import becca from "../../becca/becca";import type { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/commons";import type { Request } from "express";-import { HTMLElement, parse, TextNode } from "node-html-parser";-import { EXCERPT_CHAR_LIMIT, findLlmChatExcerpts } from "../../services/llm_chat_excerpts";+import { findExcerpts, findLlmChatExcerpts } from "../../services/backlink_excerpts";interface TreeLink {sourceNoteId: string;@@ -244,104 +243,6 @@ function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<st}}-function removeImages(document: HTMLElement) {- const images = document.getElementsByTagName("img");- for (const image of images) {- image.remove();- }-}--type ElementOrText = HTMLElement | TextNode;--export function findExcerpts(sourceNote: BNote, referencedNoteId: string) {- const html = sourceNote.getContent();- const document = parse(html.toString());-- const excerpts: string[] = [];-- removeImages(document);-- for (const linkEl of document.querySelectorAll("a")) {- const href = linkEl.getAttribute("href");-- if (!href || !href.endsWith(referencedNoteId)) {- continue;- }-- linkEl.classList.add("backlink-link");-- let centerEl: HTMLElement = linkEl;-- while (centerEl.tagName !== "BODY" && centerEl.parentNode && (centerEl.parentNode?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {- centerEl = centerEl.parentNode;- }-- const excerptEls: ElementOrText[] = [centerEl];- let excerptLength = centerEl.textContent?.length || 0;- let left: ElementOrText = centerEl;- let right: ElementOrText = centerEl;-- while (excerptLength < EXCERPT_CHAR_LIMIT) {- let added = false;-- const prev: HTMLElement | null = left.previousElementSibling;-- if (prev) {- const prevText = prev.textContent || "";-- if (prevText.length + excerptLength > EXCERPT_CHAR_LIMIT) {- const prefix = prevText.substr(prevText.length - (EXCERPT_CHAR_LIMIT - excerptLength));-- const textNode = new TextNode(`…${prefix}`);- excerptEls.unshift(textNode);-- break;- }-- left = prev;- excerptEls.unshift(left);- excerptLength += prevText.length;- added = true;- }-- const next: HTMLElement | null = right.nextElementSibling;-- if (next) {- const nextText = next.textContent;-- if (nextText && nextText.length + excerptLength > EXCERPT_CHAR_LIMIT) {- const suffix = nextText.substr(nextText.length - (EXCERPT_CHAR_LIMIT - excerptLength));-- const textNode = new TextNode(`${suffix}…`);- excerptEls.push(textNode);-- break;- }-- right = next;- excerptEls.push(right);- excerptLength += nextText?.length || 0;- added = true;- }-- if (!added) {- break;- }- }-- const excerptWrapper = new HTMLElement("div", {});- excerptWrapper.classList.add("ck-content");- excerptWrapper.classList.add("backlink-excerpt");-- for (const childEl of excerptEls) {- excerptWrapper.appendChild(childEl);- }-- excerpts.push(excerptWrapper.outerHTML);- }- return excerpts;-}-function getFilteredBacklinks(note: BNote): BAttribute[] {return (note@@ -372,7 +273,7 @@ function getBacklinks(req: Request<{ noteId: string }>): BacklinksResponse {const excerpts = sourceNote.type === "llmChat"? findLlmChatExcerpts(sourceNote.getContent().toString(), noteId)- : findExcerpts(sourceNote, noteId);+ : findExcerpts(sourceNote.getContent().toString(), noteId);// A chat that references the note only through tool calls has no quotable prose;// name the relation instead, as for other excerpt-less sources.diff --git a/packages/trilium-core/src/services/llm_chat_excerpts.spec.ts b/packages/trilium-core/src/services/backlink_excerpts.spec.tssimilarity index 52%rename from packages/trilium-core/src/services/llm_chat_excerpts.spec.tsrename to packages/trilium-core/src/services/backlink_excerpts.spec.tsindex b84b5aff04..b577294c8f 100644--- a/packages/trilium-core/src/services/llm_chat_excerpts.spec.ts+++ b/packages/trilium-core/src/services/backlink_excerpts.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { buildNote } from "../test/becca_easy_mocking";-import { findLlmChatExcerpts } from "./llm_chat_excerpts";+import { findLlmChatExcerpts } from "./backlink_excerpts";function chatContent(messages: unknown[]) {return JSON.stringify({ messages });@@ -22,39 +22,63 @@ describe("findLlmChatExcerpts", () => {}]), "excTarget");- expect(excerpts).toEqual([- `<div class="ck-content backlink-excerpt"><p>I found 1 < 2 results in ` +- `<a class="reference-link backlink-link" href="#root/excTarget">Chat target</a> next to ` +- `<a class="reference-link" href="#root/excOther">Other <note></a>.</p></div>`- ]);+ expect(excerpts).toHaveLength(1);+ expect(excerpts[0]).toMatch(/^<div class="ck-content backlink-excerpt">/);+ expect(excerpts[0]).toContain("I found 1 < 2 results in");+ expect(excerpts[0]).toContain(`<a class="reference-link backlink-link" href="#root/excTarget">Chat target</a>`);+ expect(excerpts[0]).toContain(`<a class="reference-link" href="#root/excOther">Other <note></a>`);});- it("titles a link to an unknown note with the raw ID", () => {+ it("renders the markdown instead of quoting it verbatim", () => {+ buildNote({ id: "excMd", title: "Md target" });+const excerpts = findLlmChatExcerpts(chatContent([- { role: "assistant", content: [ { type: "text", content: "See [[excMissing]]." } ] }+ {+ role: "assistant",+ content: [+ { type: "text", content: "It is **very** relevant to [[excMd]]:\n\n- one\n- two" }+ ]+ }+ ]), "excMd");++ expect(excerpts[0]).toContain("<strong>very</strong>");+ expect(excerpts[0]).toContain("<li>one</li>");+ expect(excerpts[0]).not.toContain("**");+ });++ it("keeps a regular markdown link's own text and titles a link to an unknown note with the raw ID", () => {+ const excerpts = findLlmChatExcerpts(chatContent([+ {+ role: "assistant",+ content: [+ { type: "text", content: "See [my name](#root/excMissing) and [[excMissing]]." }+ ]+ }]), "excMissing");- expect(excerpts[0]).toContain(`>excMissing</a>`);+ expect(excerpts).toHaveLength(2);+ expect(excerpts[0]).toContain(">my name</a>");+ expect(excerpts[1]).toContain(">excMissing</a>");});- it("truncates long text runs with ellipses, one excerpt per mention", () => {+ it("truncates long neighboring paragraphs with ellipses, one excerpt per mention", () => {buildNote({ id: "excLong", title: "Long target" });const excerpts = findLlmChatExcerpts(chatContent([{role: "assistant",content: [- { type: "text", content: `${"a".repeat(260)} [[excLong]] ${"b".repeat(260)}` },+ { type: "text", content: `${"a".repeat(260)}\n\nHere: [[excLong]]\n\n${"b".repeat(260)}` },{ type: "text", content: "Also see [[excLong]]." }]}]), "excLong");expect(excerpts).toHaveLength(2);- // Like findExcerpts for text notes, expansion stops at the first truncated run, so the- // whole budget goes to the text preceding the link and none is left for the text after.- expect(excerpts[0]).toMatch(/…a+ <a class="reference-link backlink-link"/);- expect(excerpts[0]).not.toMatch(/b{3}/);+ // Like text-note excerpts, expansion stops at the first truncated paragraph, so the+ // budget goes to the text preceding the link.+ expect(excerpts[0]).toMatch(/…a+/);+ expect(excerpts[0]).toContain(`<a class="reference-link backlink-link" href="#root/excLong">Long target</a>`);expect(excerpts[1]).toContain("Also see <a");});diff --git a/packages/trilium-core/src/services/backlink_excerpts.ts b/packages/trilium-core/src/services/backlink_excerpts.tsnew file mode 100644index 0000000000..05e5c56bd7--- /dev/null+++ b/packages/trilium-core/src/services/backlink_excerpts.ts@@ -0,0 +1,189 @@+/**+ * Extracts backlink content previews: quotes what surrounds each link pointing at the+ * referenced note, as `ck-content backlink-excerpt` fragments the backlinks UI renders.+ *+ * {@link findExcerpts} works on any HTML that marks its note links as `href="…#root…/<noteId>"`+ * anchors — a text note's content directly. {@link findLlmChatExcerpts} brings `llmChat` notes+ * to that same shape first: their assistant prose is markdown, rendered to HTML through the+ * shared pipeline the chat UI uses, with wiki-link anchors retitled from note ID to note title.+ */++import { renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";+import { HTMLElement, parse, TextNode } from "node-html-parser";++import becca from "../becca/becca";+import { sanitizeHtml } from "./sanitizer.js";+import { escapeHtml } from "./utils/index";++/** Character budget of one excerpt. */+export const EXCERPT_CHAR_LIMIT = 200;++type ElementOrText = HTMLElement | TextNode;++export function findExcerpts(html: string, referencedNoteId: string): string[] {+ const document = parse(html);++ const excerpts: string[] = [];++ removeImages(document);++ for (const linkEl of document.querySelectorAll("a")) {+ const href = linkEl.getAttribute("href");++ if (!href || !href.endsWith(referencedNoteId)) {+ continue;+ }++ linkEl.classList.add("backlink-link");++ let centerEl: HTMLElement = linkEl;++ while (centerEl.tagName !== "BODY" && centerEl.parentNode && (centerEl.parentNode?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {+ centerEl = centerEl.parentNode;+ }++ const excerptEls: ElementOrText[] = [centerEl];+ let excerptLength = centerEl.textContent?.length || 0;+ let left: ElementOrText = centerEl;+ let right: ElementOrText = centerEl;++ while (excerptLength < EXCERPT_CHAR_LIMIT) {+ let added = false;++ const prev: HTMLElement | null = left.previousElementSibling;++ if (prev) {+ const prevText = prev.textContent || "";++ if (prevText.length + excerptLength > EXCERPT_CHAR_LIMIT) {+ const prefix = prevText.substr(prevText.length - (EXCERPT_CHAR_LIMIT - excerptLength));++ const textNode = new TextNode(`…${prefix}`);+ excerptEls.unshift(textNode);++ break;+ }++ left = prev;+ excerptEls.unshift(left);+ excerptLength += prevText.length;+ added = true;+ }++ const next: HTMLElement | null = right.nextElementSibling;++ if (next) {+ const nextText = next.textContent;++ if (nextText && nextText.length + excerptLength > EXCERPT_CHAR_LIMIT) {+ const suffix = nextText.substr(nextText.length - (EXCERPT_CHAR_LIMIT - excerptLength));++ const textNode = new TextNode(`${suffix}…`);+ excerptEls.push(textNode);++ break;+ }++ right = next;+ excerptEls.push(right);+ excerptLength += nextText?.length || 0;+ added = true;+ }++ if (!added) {+ break;+ }+ }++ const excerptWrapper = new HTMLElement("div", {});+ excerptWrapper.classList.add("ck-content");+ excerptWrapper.classList.add("backlink-excerpt");++ for (const childEl of excerptEls) {+ excerptWrapper.appendChild(childEl);+ }++ excerpts.push(excerptWrapper.outerHTML);+ }+ return excerpts;+}++function removeImages(document: HTMLElement) {+ const images = document.getElementsByTagName("img");+ for (const image of images) {+ image.remove();+ }+}++/**+ * The `llmChat` entry point. A chat stores its whole conversation as one JSON blob+ * (`{ messages: [...] }`), and its internalLink relations come from `[[noteId]]` wiki-links in+ * assistant text blocks (see `findLlmChatLinks` in services/notes.ts) — so those blocks are+ * rendered to HTML and quoted by {@link findExcerpts} like any other content. A chat that+ * references the note purely through tool calls has nothing quotable and yields no excerpts.+ */+export function findLlmChatExcerpts(jsonContent: string, referencedNoteId: string): string[] {+ const markdown = collectAssistantProse(jsonContent);+ if (!markdown) {+ return [];+ }++ const html = renderToHtml(markdown, "", {+ sanitize: sanitizeHtml,+ // The same href shape the chat UI renders, and the one findExcerpts matches on.+ wikiLink: { formatHref: (noteId) => `#root/${noteId}` },+ // Chat prose is a conversation, not a document with a duplicated title heading.+ demoteH1: false+ });++ return findExcerpts(titleWikiLinks(html), referencedNoteId);+}++/** Joins the assistant text blocks — the only chat content that creates internalLink relations. */+function collectAssistantProse(jsonContent: string): string {+ let parsed: { messages?: unknown[] };+ try {+ parsed = JSON.parse(jsonContent);+ } catch {+ return "";+ }+ if (!Array.isArray(parsed.messages)) {+ return "";+ }++ const blocks: string[] = [];+ for (const message of parsed.messages) {+ if (typeof message !== "object" || message === null) continue;+ const { role, content } = message as Record<string, unknown>;+ if (role !== "assistant" || !Array.isArray(content)) continue;++ for (const block of content) {+ if (typeof block !== "object" || block === null) continue;+ const b = block as Record<string, unknown>;+ if (b.type === "text" && typeof b.content === "string") {+ blocks.push(b.content);+ }+ }+ }+ // A blank line between blocks keeps them separate markdown paragraphs.+ return blocks.join("\n\n");+}++/**+ * Renames the wiki-link anchors from the note ID (all the markdown source carries) to the+ * note's title. In the chat UI this decoration happens client-side, but excerpts are rendered+ * as-is by the backlinks list, so the title has to be baked in.+ */+function titleWikiLinks(html: string): string {+ const document = parse(html);++ for (const linkEl of document.querySelectorAll(`a[href^="#root/"]`)) {+ const noteId = linkEl.getAttribute("href")?.slice("#root/".length);+ // A regular markdown link carries its own text; only a wiki-link names its target's ID.+ if (noteId && linkEl.textContent.trim() === noteId) {+ linkEl.set_content(escapeHtml(becca.notes[noteId]?.getTitleOrProtected() ?? noteId));+ }+ }++ return document.toString();+}diff --git a/packages/trilium-core/src/services/llm_chat_excerpts.ts b/packages/trilium-core/src/services/llm_chat_excerpts.tsdeleted file mode 100644index 4ddc829971..0000000000--- a/packages/trilium-core/src/services/llm_chat_excerpts.ts+++ /dev/null@@ -1,162 +0,0 @@-/**- * Builds backlink content previews for `llmChat` notes: the counterpart of `findExcerpts`- * (routes/api/note_map.ts), which does the same for `text` notes by walking their HTML.- *- * A chat stores its whole conversation as one JSON blob (`{ messages: [...] }`), and its- * internalLink relations come from `[[noteId]]` wiki-links in assistant text blocks (see- * `findLlmChatLinks` in services/notes.ts). Excerpts therefore quote the assistant prose- * around each wiki-link pointing at the referenced note; a chat that references the note- * purely through tool calls has nothing quotable and yields no excerpts.- */--import becca from "../becca/becca";-import { escapeHtml } from "./utils/index";--/** Character budget of one excerpt, shared with the text-note excerpts of note_map.ts. */-export const EXCERPT_CHAR_LIMIT = 200;--/**- * Quotes the assistant prose around each `[[noteId]]` wiki-link pointing at the referenced- * note, as `ck-content backlink-excerpt` HTML fragments (the shape the backlinks UI renders).- * Returns an empty array for unparseable content or a chat with no quotable mention.- */-export function findLlmChatExcerpts(jsonContent: string, referencedNoteId: string): string[] {- let parsed: { messages?: unknown[] };- try {- parsed = JSON.parse(jsonContent);- } catch {- return [];- }- if (!Array.isArray(parsed.messages)) {- return [];- }-- const excerpts: string[] = [];- for (const message of parsed.messages) {- if (typeof message !== "object" || message === null) continue;- const { role, content } = message as Record<string, unknown>;- if (role !== "assistant" || !Array.isArray(content)) continue;-- for (const block of content) {- if (typeof block !== "object" || block === null) continue;- const b = block as Record<string, unknown>;- if (b.type !== "text" || typeof b.content !== "string") continue;-- const tokens = tokenizeChatText(b.content);- for (let i = 0; i < tokens.length; i++) {- if (tokens[i].noteId === referencedNoteId) {- excerpts.push(buildChatExcerpt(tokens, i, referencedNoteId));- }- }- }- }- return excerpts;-}--/**- * A chat's text split into plain-text runs and `[[noteId]]` wiki-links, so an excerpt window- * can truncate text freely but never cut through a link.- */-interface ChatToken {- /** The linked note's ID for a wiki-link token, undefined for a plain text run. */- noteId?: string;- text: string;-}--const WIKI_LINK_RE = /\[\[([a-zA-Z0-9_]+)\]\]/g;--function tokenizeChatText(text: string): ChatToken[] {- const tokens: ChatToken[] = [];- let lastIndex = 0;- let match: RegExpExecArray | null;-- WIKI_LINK_RE.lastIndex = 0;- while ((match = WIKI_LINK_RE.exec(text))) {- if (match.index > lastIndex) {- tokens.push({ text: text.substring(lastIndex, match.index) });- }- tokens.push({ noteId: match[1], text: match[0] });- lastIndex = match.index + match[0].length;- }- if (lastIndex < text.length) {- tokens.push({ text: text.substring(lastIndex) });- }- return tokens;-}--/** What the token contributes to the excerpt's visible length: links show their note's title. */-function chatTokenLength(token: ChatToken): number {- return token.noteId ? chatLinkTitle(token.noteId).length : token.text.length;-}--function chatLinkTitle(noteId: string): string {- return becca.notes[noteId]?.getTitleOrProtected() ?? noteId;-}--function renderChatToken(token: ChatToken, referencedNoteId: string): string {- if (!token.noteId) {- return escapeHtml(token.text);- }- const classes = token.noteId === referencedNoteId- ? "reference-link backlink-link"- : "reference-link";- return `<a class="${classes}" href="#root/${token.noteId}">${escapeHtml(chatLinkTitle(token.noteId))}</a>`;-}--/**- * Grows a window of tokens around the matched link until {@link EXCERPT_CHAR_LIMIT}, truncating- * an overflowing text run with an ellipsis — the same expansion findExcerpts does over sibling- * DOM nodes, over chat tokens instead.- */-function buildChatExcerpt(tokens: ChatToken[], centerIndex: number, referencedNoteId: string): string {- const parts: string[] = [renderChatToken(tokens[centerIndex], referencedNoteId)];- let excerptLength = chatTokenLength(tokens[centerIndex]);- let left = centerIndex - 1;- let right = centerIndex + 1;-- while (excerptLength < EXCERPT_CHAR_LIMIT) {- let added = false;-- if (left >= 0) {- const token = tokens[left];- const tokenLength = chatTokenLength(token);-- if (tokenLength + excerptLength > EXCERPT_CHAR_LIMIT) {- if (!token.noteId) {- const prefix = token.text.substring(token.text.length - (EXCERPT_CHAR_LIMIT - excerptLength));- parts.unshift(`…${escapeHtml(prefix)}`);- }- break;- }-- parts.unshift(renderChatToken(token, referencedNoteId));- excerptLength += tokenLength;- left--;- added = true;- }-- if (right < tokens.length) {- const token = tokens[right];- const tokenLength = chatTokenLength(token);-- if (tokenLength + excerptLength > EXCERPT_CHAR_LIMIT) {- if (!token.noteId) {- const suffix = token.text.substring(0, EXCERPT_CHAR_LIMIT - excerptLength);- parts.push(`${escapeHtml(suffix)}…`);- }- break;- }-- parts.push(renderChatToken(token, referencedNoteId));- excerptLength += tokenLength;- right++;- added = true;- }-- if (!added) {- break;- }- }-- return `<div class="ck-content backlink-excerpt"><p>${parts.join("")}</p></div>`;-}