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): backlink content previews for llmChat notes
Elian Doran964ad1844414
diff --git a/packages/trilium-core/src/routes/api/note_map.spec.ts b/packages/trilium-core/src/routes/api/note_map.spec.tsindex 8f2c15b715..91ef5bf98b 100644--- a/packages/trilium-core/src/routes/api/note_map.spec.ts+++ b/packages/trilium-core/src/routes/api/note_map.spec.ts@@ -388,6 +388,76 @@ describe("Note map service (branch coverage)", () => {);expect(excerpts[0]).toContain("…");});++ function chatBacklink(sourceId: string, messages: unknown[] | string) {+ const target = buildNote({ id: `${sourceId}_t`, title: "Chat target" });+ buildNote({+ id: sourceId,+ title: "Chat",+ type: "llmChat",+ "~internalLink": target.noteId,+ content: typeof messages === "string" ? messages : JSON.stringify({ messages })+ });+ const res = note_map.getBacklinks(req(target.noteId));+ return res.find((b) => b.noteId === sourceId) as any;+ }++ it("llmChat backlinks: quotes the assistant prose around the wiki-link, links titled and escaped", () => {+ buildNote({ id: "chatOther", title: "Other <note>" });+ const backlink = chatBacklink("chatWiki", [+ { role: "user", content: "where is [[chatWiki_t]] mentioned?" },+ {+ role: "assistant",+ content: [+ { type: "text", content: "I found 1 < 2 results in [[chatWiki_t]] next to [[chatOther]]." }+ ]+ }+ ]);++ expect(backlink.relationName).toBeUndefined();+ expect(backlink.excerpts).toEqual([+ `<div class="ck-content backlink-excerpt"><p>I found 1 < 2 results in ` ++ `<a class="reference-link backlink-link" href="#root/chatWiki_t">Chat target</a> next to ` ++ `<a class="reference-link" href="#root/chatOther">Other <note></a>.</p></div>`+ ]);+ });++ it("llmChat backlinks: truncates long surrounding prose with ellipses, one excerpt per mention", () => {+ const backlink = chatBacklink("chatLong", [+ {+ role: "assistant",+ content: [+ { type: "text", content: `${"a".repeat(260)} [[chatLong_t]] ${"b".repeat(260)}` },+ { type: "text", content: "Also see [[chatLong_t]]." }+ ]+ }+ ]);++ expect(backlink.excerpts).toHaveLength(2);+ // Like findExcerpts, 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 it.+ expect(backlink.excerpts[0]).toMatch(/…a+ <a class="reference-link backlink-link"/);+ expect(backlink.excerpts[0]).not.toMatch(/b{3}/);+ expect(backlink.excerpts[1]).toContain("Also see <a");+ });++ it("llmChat backlinks: tool-call-only references and unparseable content fall back to the relation name", () => {+ const toolCallOnly = chatBacklink("chatTool", [+ {+ role: "assistant",+ content: [+ { type: "tool_call", toolCall: { input: { noteId: "chatTool_t" } } },+ // A user-role block and a non-text assistant block must not be quoted either.+ { type: "thinking", content: "peeking at [[chatTool_t]]" }+ ]+ },+ { role: "user", content: "the [[chatTool_t]] wiki-link in user prose creates no relation" }+ ]);+ expect(toolCallOnly).toEqual({ noteId: "chatTool", relationName: "internalLink" });++ const invalid = chatBacklink("chatBroken", "not JSON at all");+ expect(invalid).toEqual({ noteId: "chatBroken", relationName: "internalLink" });+ });});let api: CoreApiTester;diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.tsindex b0eef78841..71e31ff7a7 100644--- a/packages/trilium-core/src/routes/api/note_map.ts+++ b/packages/trilium-core/src/routes/api/note_map.ts@@ -5,6 +5,8 @@ import type { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/commimport type { Request } from "express";import { HTMLElement, parse, TextNode } from "node-html-parser";+import { escapeHtml } from "../../services/utils/index";+interface TreeLink {sourceNoteId: string;targetNoteId: string;@@ -341,6 +343,154 @@ export function findExcerpts(sourceNote: BNote, referencedNoteId: string) {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;++/**+ * The llmChat counterpart of {@link findExcerpts}: quotes the assistant prose around each+ * `[[noteId]]` wiki-link pointing at the referenced note. Only assistant text blocks are+ * scanned — they are what creates a chat's internalLink relations in the first place (see+ * `findLlmChatLinks` in services/notes.ts) — so a chat that references the note purely+ * through tool calls yields no excerpts.+ */+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;+}++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>`;+}+function getFilteredBacklinks(note: BNote): BAttribute[] {return (note@@ -358,8 +508,9 @@ function getBacklinks(req: Request<{ noteId: string }>): BacklinksResponse {return getFilteredBacklinks(note).map((backlink) => {const sourceNote = backlink.note;+ const supportsExcerpts = sourceNote.type === "text" || sourceNote.type === "llmChat";- if (sourceNote.type !== "text" || backlinksWithExcerptCount > 50) {+ if (!supportsExcerpts || backlinksWithExcerptCount > 50) {return {noteId: sourceNote.noteId,relationName: backlink.name@@ -368,7 +519,19 @@ function getBacklinks(req: Request<{ noteId: string }>): BacklinksResponse {backlinksWithExcerptCount++;- const excerpts = findExcerpts(sourceNote, noteId);+ const excerpts = sourceNote.type === "llmChat"+ ? findLlmChatExcerpts(sourceNote.getContent().toString(), noteId)+ : findExcerpts(sourceNote, 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.+ if (sourceNote.type === "llmChat" && excerpts.length === 0) {+ return {+ noteId: sourceNote.noteId,+ relationName: backlink.name+ } satisfies BacklinksResponse[number];+ }+return {noteId: sourceNote.noteId,excerpts