Skip to content

Build your personal knowledge base with Trilium Notes

refactor(core): extract llmChat backlink excerpts into a service module

Elian Doran010bbbe8f2f9
diff --git a/packages/trilium-core/src/routes/api/note_map.spec.ts b/packages/trilium-core/src/routes/api/note_map.spec.ts
index 91ef5bf98b..b865174003 100644
--- a/packages/trilium-core/src/routes/api/note_map.spec.ts
+++ b/packages/trilium-core/src/routes/api/note_map.spec.ts
@@ -402,61 +402,29 @@ describe("Note map service (branch coverage)", () => {
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>" });
+ // The excerpt HTML itself is covered by services/llm_chat_excerpts.spec.ts;
+ // these only pin how getBacklinks routes llmChat sources.
+ it("llmChat backlinks: a quotable mention yields excerpts instead of the relation name", () => {
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]]." }
- ]
+ content: [ { type: "text", content: "I found it in [[chatWiki_t]]." } ]
}
]);
expect(backlink.relationName).toBeUndefined();
- expect(backlink.excerpts).toEqual([
- `<div class="ck-content backlink-excerpt"><p>I found 1 &lt; 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 &lt;note&gt;</a>.</p></div>`
- ]);
+ expect(backlink.excerpts).toHaveLength(1);
+ expect(backlink.excerpts[0]).toContain(`<a class="reference-link backlink-link" href="#root/chatWiki_t">`);
});
- 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", () => {
+ it("llmChat backlinks: an excerpt-less chat falls 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" }
+ content: [ { type: "tool_call", toolCall: { input: { noteId: "chatTool_t" } } } ]
+ }
]);
expect(toolCallOnly).toEqual({ noteId: "chatTool", relationName: "internalLink" });
-
- const invalid = chatBacklink("chatBroken", "not JSON at all");
- expect(invalid).toEqual({ noteId: "chatBroken", relationName: "internalLink" });
});
});
diff --git a/packages/trilium-core/src/routes/api/note_map.ts b/packages/trilium-core/src/routes/api/note_map.ts
index 71e31ff7a7..139411debb 100644
--- a/packages/trilium-core/src/routes/api/note_map.ts
+++ b/packages/trilium-core/src/routes/api/note_map.ts
@@ -5,7 +5,7 @@ import type { BacklinkCountResponse, BacklinksResponse } from "@triliumnext/comm
import type { Request } from "express";
import { HTMLElement, parse, TextNode } from "node-html-parser";
-import { escapeHtml } from "../../services/utils/index";
+import { EXCERPT_CHAR_LIMIT, findLlmChatExcerpts } from "../../services/llm_chat_excerpts";
interface TreeLink {
sourceNoteId: string;
@@ -251,7 +251,6 @@ function removeImages(document: HTMLElement) {
}
}
-const EXCERPT_CHAR_LIMIT = 200;
type ElementOrText = HTMLElement | TextNode;
export function findExcerpts(sourceNote: BNote, referencedNoteId: string) {
@@ -343,154 +342,6 @@ 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
diff --git a/packages/trilium-core/src/services/llm_chat_excerpts.spec.ts b/packages/trilium-core/src/services/llm_chat_excerpts.spec.ts
new file mode 100644
index 0000000000..b84b5aff04
--- /dev/null
+++ b/packages/trilium-core/src/services/llm_chat_excerpts.spec.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+
+import { buildNote } from "../test/becca_easy_mocking";
+import { findLlmChatExcerpts } from "./llm_chat_excerpts";
+
+function chatContent(messages: unknown[]) {
+ return JSON.stringify({ messages });
+}
+
+describe("findLlmChatExcerpts", () => {
+ it("quotes the assistant prose around the wiki-link, links titled and text escaped", () => {
+ buildNote({ id: "excTarget", title: "Chat target" });
+ buildNote({ id: "excOther", title: "Other <note>" });
+
+ const excerpts = findLlmChatExcerpts(chatContent([
+ { role: "user", content: "where is [[excTarget]] mentioned?" },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", content: "I found 1 < 2 results in [[excTarget]] next to [[excOther]]." }
+ ]
+ }
+ ]), "excTarget");
+
+ expect(excerpts).toEqual([
+ `<div class="ck-content backlink-excerpt"><p>I found 1 &lt; 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 &lt;note&gt;</a>.</p></div>`
+ ]);
+ });
+
+ it("titles a link to an unknown note with the raw ID", () => {
+ const excerpts = findLlmChatExcerpts(chatContent([
+ { role: "assistant", content: [ { type: "text", content: "See [[excMissing]]." } ] }
+ ]), "excMissing");
+
+ expect(excerpts[0]).toContain(`>excMissing</a>`);
+ });
+
+ it("truncates long text runs 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: "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}/);
+ expect(excerpts[1]).toContain("Also see <a");
+ });
+
+ it("quotes nothing from tool calls, thinking blocks, user prose, or broken content", () => {
+ const quiet = chatContent([
+ {
+ role: "assistant",
+ content: [
+ { type: "tool_call", toolCall: { input: { noteId: "excQuiet" } } },
+ { type: "thinking", content: "peeking at [[excQuiet]]" }
+ ]
+ },
+ { role: "user", content: "the [[excQuiet]] wiki-link in user prose creates no relation" }
+ ]);
+
+ expect(findLlmChatExcerpts(quiet, "excQuiet")).toEqual([]);
+ expect(findLlmChatExcerpts("not JSON at all", "excQuiet")).toEqual([]);
+ expect(findLlmChatExcerpts(`{"messages": "not an array"}`, "excQuiet")).toEqual([]);
+ });
+});
diff --git a/packages/trilium-core/src/services/llm_chat_excerpts.ts b/packages/trilium-core/src/services/llm_chat_excerpts.ts
new file mode 100644
index 0000000000..4ddc829971
--- /dev/null
+++ b/packages/trilium-core/src/services/llm_chat_excerpts.ts
@@ -0,0 +1,162 @@
+/**
+ * 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>`;
+}