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): basic support for internal links
Elian Doranfb60efd624ca
diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex 1a71d34d8c..3a35c2414e 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -3,7 +3,7 @@ import becca from "../becca/becca.js";import { buildNote } from "../test/becca_easy_mocking.js";import { randomString } from "./utils.js";import BAttribute from "../becca/entities/battribute.js";-import { checkImageAttachments, findBookmarks, saveLinks } from "./notes.js";+import { checkImageAttachments, findBookmarks, findLlmChatLinks, saveLinks } from "./notes.js";vi.mock("./sql.js", () => ({default: {@@ -322,4 +322,246 @@ describe("saveLinks", () => {expect(linkA.markAsDeleted).not.toHaveBeenCalled();expect(linkB.markAsDeleted).not.toHaveBeenCalled();});++ describe("llmChat notes", () => {+ function makeChatContent(messages: unknown[]) {+ return JSON.stringify({ version: 1, messages });+ }++ it("detects [[noteId]] wiki-links in assistant text blocks", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const targetA = buildNote({ title: "Note A" });+ const targetB = buildNote({ title: "Note B" });+ becca.notes[targetA.noteId] = targetA;+ becca.notes[targetB.noteId] = targetB;++ const linkA = makeLinkRelation(note.noteId, "internalLink", targetA.noteId);+ const linkB = makeLinkRelation(note.noteId, "internalLink", targetB.noteId);+ note.getRelations = () => [linkA, linkB];++ const content = makeChatContent([+ { id: "1", role: "user", content: "Show me notes" },+ {+ id: "2", role: "assistant", content: [+ { type: "text", content: `Here are your notes: [[${targetA.noteId}]] and [[${targetB.noteId}]]` }+ ]+ }+ ]);+ saveLinks(note, content);++ expect(linkA.markAsDeleted).not.toHaveBeenCalled();+ expect(linkB.markAsDeleted).not.toHaveBeenCalled();+ });++ it("detects noteId in tool call inputs", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const target = buildNote({ title: "Target Note" });+ becca.notes[target.noteId] = target;++ const link = makeLinkRelation(note.noteId, "internalLink", target.noteId);+ note.getRelations = () => [link];++ const content = makeChatContent([+ {+ id: "1", role: "assistant", content: [+ {+ type: "tool_call", toolCall: {+ id: "tc1", toolName: "get_note",+ input: { noteId: target.noteId },+ result: "{}"+ }+ }+ ]+ }+ ]);+ saveLinks(note, content);++ expect(link.markAsDeleted).not.toHaveBeenCalled();+ });++ it("detects parentNoteId in tool call inputs", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const parent = buildNote({ title: "Parent Note" });+ becca.notes[parent.noteId] = parent;++ const link = makeLinkRelation(note.noteId, "internalLink", parent.noteId);+ note.getRelations = () => [link];++ const content = makeChatContent([+ {+ id: "1", role: "assistant", content: [+ {+ type: "tool_call", toolCall: {+ id: "tc1", toolName: "create_note",+ input: { parentNoteId: parent.noteId, title: "New" },+ result: "{}"+ }+ }+ ]+ }+ ]);+ saveLinks(note, content);++ expect(link.markAsDeleted).not.toHaveBeenCalled();+ });++ it("detects links from both text blocks and tool calls", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const targetA = buildNote({ title: "Note A" });+ const targetB = buildNote({ title: "Note B" });+ becca.notes[targetA.noteId] = targetA;+ becca.notes[targetB.noteId] = targetB;++ const linkA = makeLinkRelation(note.noteId, "internalLink", targetA.noteId);+ const linkB = makeLinkRelation(note.noteId, "internalLink", targetB.noteId);+ note.getRelations = () => [linkA, linkB];++ const content = makeChatContent([+ {+ id: "1", role: "assistant", content: [+ {+ type: "tool_call", toolCall: {+ id: "tc1", toolName: "get_note",+ input: { noteId: targetA.noteId },+ result: "{}"+ }+ },+ { type: "text", content: `See [[${targetB.noteId}]] for details.` }+ ]+ }+ ]);+ saveLinks(note, content);++ expect(linkA.markAsDeleted).not.toHaveBeenCalled();+ expect(linkB.markAsDeleted).not.toHaveBeenCalled();+ });++ it("deletes links that are no longer in the chat content", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const removedTarget = buildNote({ title: "Removed" });+ becca.notes[removedTarget.noteId] = removedTarget;++ const staleLink = makeLinkRelation(note.noteId, "internalLink", removedTarget.noteId);+ note.getRelations = () => [staleLink];++ const content = makeChatContent([+ { id: "1", role: "user", content: "Hello" },+ { id: "2", role: "assistant", content: [{ type: "text", content: "Hi there!" }] }+ ]);+ saveLinks(note, content);++ expect(staleLink.markAsDeleted).toHaveBeenCalled();+ });++ it("ignores user messages (does not extract links from them)", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ const target = buildNote({ title: "Target" });+ becca.notes[target.noteId] = target;++ const staleLink = makeLinkRelation(note.noteId, "internalLink", target.noteId);+ note.getRelations = () => [staleLink];++ const content = makeChatContent([+ { id: "1", role: "user", content: `Check [[${target.noteId}]]` }+ ]);+ saveLinks(note, content);++ expect(staleLink.markAsDeleted).toHaveBeenCalled();+ });++ it("handles invalid JSON content gracefully", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ note.getRelations = () => [];++ expect(() => saveLinks(note, "not valid json")).not.toThrow();+ });++ it("handles empty messages array", () => {+ const note = buildNote({ title: "Chat", type: "llmChat", mime: "application/json" });+ note.getRelations = () => [];++ expect(() => saveLinks(note, JSON.stringify({ version: 1, messages: [] }))).not.toThrow();+ });+ });+});++describe("findLlmChatLinks", () => {+ it("extracts wiki-links from assistant text blocks", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ const content = JSON.stringify({+ messages: [{+ role: "assistant",+ content: [{ type: "text", content: "See [[abc123]] and [[def456]]" }]+ }]+ });+ findLlmChatLinks(content, links);++ expect(links).toEqual([+ { name: "internalLink", value: "abc123" },+ { name: "internalLink", value: "def456" }+ ]);+ });++ it("extracts noteId and parentNoteId from tool call inputs", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ const content = JSON.stringify({+ messages: [{+ role: "assistant",+ content: [+ {+ type: "tool_call",+ toolCall: { id: "t1", toolName: "get_note", input: { noteId: "noteA" } }+ },+ {+ type: "tool_call",+ toolCall: { id: "t2", toolName: "create_note", input: { parentNoteId: "noteB", title: "X" } }+ }+ ]+ }]+ });+ findLlmChatLinks(content, links);++ expect(links).toEqual([+ { name: "internalLink", value: "noteA" },+ { name: "internalLink", value: "noteB" }+ ]);+ });++ it("skips user and system messages", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ const content = JSON.stringify({+ messages: [+ { role: "user", content: "Check [[abc123]]" },+ { role: "system", content: "You have [[def456]]" }+ ]+ });+ findLlmChatLinks(content, links);++ expect(links).toEqual([]);+ });++ it("returns nothing for invalid JSON", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ findLlmChatLinks("broken json {", links);++ expect(links).toEqual([]);+ });++ it("returns nothing when messages is missing", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ findLlmChatLinks(JSON.stringify({ version: 1 }), links);++ expect(links).toEqual([]);+ });++ it("handles legacy string content in assistant messages", () => {+ const links: { name: "internalLink" | "imageLink" | "includeNoteLink" | "relationMapLink"; value: string }[] = [];+ const content = JSON.stringify({+ messages: [{ role: "assistant", content: "Some text with [[abc123]]" }]+ });+ findLlmChatLinks(content, links);++ // Legacy string content is not an array of blocks, so it's skipped+ expect(links).toEqual([]);+ });});diff --git a/apps/server/src/services/notes.ts b/apps/server/src/services/notes.tsindex 3a6a3c86c5..16c7ee3907 100644--- a/apps/server/src/services/notes.ts+++ b/apps/server/src/services/notes.ts@@ -1,3 +1,3 @@import { note_service } from "@triliumnext/core";-export { checkImageAttachments, findBookmarks, saveLinks } from "@triliumnext/core/src/services/notes.js";+export { checkImageAttachments, findBookmarks, findLlmChatLinks, saveLinks } from "@triliumnext/core/src/services/notes.js";export default note_service;diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 1eef4a8fe9..9d8b3e29bd 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -611,6 +611,60 @@ function findMarkdownInternalLinks(content: string, foundLinks: FoundLink[]) {}}+/**+ * Extract internal-link note IDs from an llmChat note's JSON content.+ *+ * Two sources are scanned:+ * 1. `[[noteId]]` wiki-links inside assistant text blocks+ * 2. `noteId` / `parentNoteId` fields in tool-call inputs+ */+export function findLlmChatLinks(content: string, foundLinks: FoundLink[]) {+ let parsed: { messages?: unknown[] };+ try {+ parsed = JSON.parse(content);+ } catch {+ return;+ }++ if (!Array.isArray(parsed.messages)) {+ return;+ }++ const wikiLinkRe = /\[\[([a-zA-Z0-9_]+)\]\]/g;++ for (const msg of parsed.messages) {+ if (typeof msg !== "object" || msg === null) continue;+ const { role, content: msgContent } = msg as Record<string, unknown>;++ if (role !== "assistant" || !Array.isArray(msgContent)) continue;++ for (const block of msgContent) {+ if (typeof block !== "object" || block === null) continue;+ const b = block as Record<string, unknown>;++ if (b.type === "text" && typeof b.content === "string") {+ let match;+ while ((match = wikiLinkRe.exec(b.content))) {+ foundLinks.push({ name: "internalLink", value: match[1] });+ }+ } else if (b.type === "tool_call") {+ const toolCall = b.toolCall as Record<string, unknown> | undefined;+ if (!toolCall || typeof toolCall !== "object") continue;++ const input = toolCall.input as Record<string, unknown> | undefined;+ if (input && typeof input === "object") {+ if (typeof input.noteId === "string" && input.noteId) {+ foundLinks.push({ name: "internalLink", value: input.noteId });+ }+ if (typeof input.parentNoteId === "string" && input.parentNoteId) {+ foundLinks.push({ name: "internalLink", value: input.parentNoteId });+ }+ }+ }+ }+ }+}+function findIncludeNoteLinks(content: string, foundLinks: FoundLink[]) {const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;let match;@@ -824,7 +878,7 @@ function saveAttachments(note: BNote, content: string) {export function saveLinks(note: BNote, content: string | Uint8Array) {- if ((note.type !== "text" && note.type !== "relationMap" && !note.isMarkdown()) || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {+ if ((note.type !== "text" && note.type !== "relationMap" && note.type !== "llmChat" && !note.isMarkdown()) || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {return {forceFrontendReload: false,content@@ -850,6 +904,8 @@ export function saveLinks(note: BNote, content: string | Uint8Array) {({ forceFrontendReload, content } = checkImageAttachments(note, content));} else if (note.type === "relationMap" && typeof content === "string") {findRelationMapLinks(content, foundLinks);+ } else if (note.type === "llmChat" && typeof content === "string") {+ findLlmChatLinks(content, foundLinks);} else {throw new Error(`Unrecognized type '${note.type}'`);}