Skip to content

Build your personal knowledge base with Trilium Notes

app: make AI chat notes searchable

Adorian Doran35f83d72b77c
diff --git a/packages/commons/src/lib/llm/extract_chat_text.spec.ts b/packages/commons/src/lib/llm/extract_chat_text.spec.ts
new file mode 100644
index 0000000000..391231fdc1
--- /dev/null
+++ b/packages/commons/src/lib/llm/extract_chat_text.spec.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+
+import { extractLlmChatText } from "./extract_chat_text.js";
+
+describe("extractLlmChatText", () => {
+ it("returns an empty string for invalid or empty content", () => {
+ expect(extractLlmChatText("")).toEqual("");
+ expect(extractLlmChatText("{")).toEqual("");
+ expect(extractLlmChatText("{}")).toEqual("");
+ expect(extractLlmChatText(`{ "messages": null }`)).toEqual("");
+ });
+
+ it("extracts plain-string message content", () => {
+ const content = JSON.stringify({
+ version: 1,
+ messages: [
+ { id: "1", role: "user", content: "How do I search notes?" },
+ { id: "2", role: "assistant", content: "Use the quick search bar." }
+ ]
+ });
+ expect(extractLlmChatText(content)).toEqual("How do I search notes? Use the quick search bar.");
+ });
+
+ it("extracts text from content blocks and ignores tool calls and attachments", () => {
+ const content = JSON.stringify({
+ version: 1,
+ messages: [
+ {
+ id: "1",
+ role: "assistant",
+ content: [
+ { type: "text", content: "First part." },
+ { type: "tool_call", toolCall: { id: "t1", toolName: "search_notes", input: {} } },
+ { type: "image", attachmentId: "a1", mime: "image/png", title: "diagram", url: "..." },
+ { type: "text", content: "Second part." }
+ ]
+ }
+ ]
+ });
+ expect(extractLlmChatText(content)).toEqual("First part. Second part.");
+ });
+
+ it("skips thinking and error turns", () => {
+ const content = JSON.stringify({
+ version: 1,
+ messages: [
+ { id: "1", role: "assistant", type: "thinking", content: "Let me reason about this." },
+ { id: "2", role: "assistant", type: "error", content: "Provider timed out." },
+ { id: "3", role: "assistant", type: "message", content: "Here is the answer." }
+ ]
+ });
+ expect(extractLlmChatText(content)).toEqual("Here is the answer.");
+ });
+});
diff --git a/packages/commons/src/lib/llm/extract_chat_text.ts b/packages/commons/src/lib/llm/extract_chat_text.ts
new file mode 100644
index 0000000000..b935e76e6e
--- /dev/null
+++ b/packages/commons/src/lib/llm/extract_chat_text.ts
@@ -0,0 +1,66 @@
+/**
+ * Extracts the plain conversation text from an LLM chat note's JSON content for
+ * full-text search indexing. An `llmChat` note stores its whole conversation as a
+ * single `application/json` blob (see `LlmChatContent` in the client's `llm_chat_types`);
+ * search must surface the readable prose, not the surrounding JSON metadata (roles,
+ * timestamps, tool-call bookkeeping, attachment references).
+ *
+ * Only user/assistant/system prose is kept: thinking and error turns, tool calls, and
+ * image/file references are skipped. Returns an empty string for invalid or empty content.
+ *
+ * The search preprocessor runs `normalize()` (lowercase + diacritic removal) on the raw
+ * content before calling this, so both keys and values arrive lowercased — the keys accessed
+ * here (`messages`, `content`, `type`) are already lowercase in the source, so this keeps
+ * working either way.
+ */
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+/**
+ * Parses the raw JSON content of an `llmChat` note and returns the conversation's
+ * readable text as a single space-separated string.
+ */
+export function extractLlmChatText(jsonContent: string): string {
+ let data: any;
+ try {
+ data = JSON.parse(jsonContent);
+ } catch {
+ return "";
+ }
+
+ const messages = data?.messages;
+ if (!Array.isArray(messages)) {
+ return "";
+ }
+
+ const parts: string[] = [];
+ for (const message of messages) {
+ // Skip internal reasoning and error turns — they are not part of the conversation.
+ if (message?.type === "thinking" || message?.type === "error") {
+ continue;
+ }
+
+ const text = extractMessageText(message?.content);
+ if (text) {
+ parts.push(text);
+ }
+ }
+
+ return parts.join(" ").trim();
+}
+
+/** Flattens a message's content (plain string or ordered content blocks) to its text. */
+function extractMessageText(content: any): string {
+ if (typeof content === "string") {
+ return content;
+ }
+ if (!Array.isArray(content)) {
+ return "";
+ }
+
+ // Keep only text blocks; drop tool calls and image/file references.
+ return content
+ .filter((block: any) => block?.type === "text" && typeof block.content === "string")
+ .map((block: any) => block.content)
+ .join(" ");
+}
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
index 18a2b45cca..996c731b2f 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
@@ -83,7 +83,7 @@ class NoteContentFulltextExp extends Expression {
for (const row of getSql().iterateRows<SearchRow>(`
SELECT noteId, type, mime, content, isProtected
FROM notes JOIN blobs USING (blobId)
- WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap', 'spreadsheet')
+ WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap', 'spreadsheet', 'llmChat')
AND isDeleted = 0
AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}`)) {
this.findInText(row, inputNoteSet, resultNoteSet);
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts
index acce9d5f6c..0704a8102d 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts
@@ -37,4 +37,25 @@ describe("Canvas preprocessing", () => {
expect(preprocessContent(`{ "elements": [ { "type": "text", "text": "Hello" } ] }`, type, mime)).toEqual("hello");
expect(preprocessContent(`{ "elements": [ { "type": "text" }, { "type": "text", "text": "World" }, { "type": "rectangle", "text": "Ignored" } ] }`, type, mime)).toEqual("world");
});
+});
+
+describe("LLM chat preprocessing", () => {
+ const type: NoteType = "llmChat";
+ const mime = "application/json";
+
+ it("supports empty / invalid JSON", () => {
+ expect(preprocessContent("{}", type, mime)).toEqual("");
+ expect(preprocessContent("", type, mime)).toEqual("");
+ });
+
+ it("reads conversation prose and skips metadata", () => {
+ const chat = JSON.stringify({
+ version: 1,
+ messages: [
+ { id: "1", role: "user", content: "What is a Branch?" },
+ { id: "2", role: "assistant", content: [ { type: "text", content: "A parent-child link." } ] }
+ ]
+ });
+ expect(preprocessContent(chat, type, mime)).toEqual("what is a branch? a parent-child link.");
+ });
});
\ No newline at end of file
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
index 61560846c5..9224e8a74d 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
@@ -1,3 +1,4 @@
+import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";
import { extractSpreadsheetText } from "@triliumnext/commons/src/lib/spreadsheet/extract_text.js";
import striptags from "striptags";
import { normalizeSearchText } from "../utils/text_utils";
@@ -19,6 +20,8 @@ export default function preprocessContent(rawContent: string | Uint8Array, type:
content = processCanvasContent(content);
} else if (type === "spreadsheet" && mime === "application/json") {
content = extractSpreadsheetText(content);
+ } else if (type === "llmChat" && mime === "application/json") {
+ content = extractLlmChatText(content);
}
return content.trim();
diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.ts
index 4a738ef939..3da446e5d9 100644
--- a/packages/trilium-core/src/services/search/services/search.ts
+++ b/packages/trilium-core/src/services/search/services/search.ts
@@ -1,3 +1,4 @@
+import { extractLlmChatText } from "@triliumnext/commons/src/lib/llm/extract_chat_text.js";
import normalizeString from "normalize-strings";
import striptags from "striptags";
@@ -470,7 +471,7 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLength
try {
let content: string | undefined;
- if (["text", "code", "mermaid", "canvas", "mindMap"].includes(note.type)) {
+ if (["text", "code", "mermaid", "canvas", "mindMap", "llmChat"].includes(note.type)) {
const raw = note.getContent();
if (raw && typeof raw === "string") {
content = raw;
@@ -498,6 +499,12 @@ function extractContentSnippet(noteId: string, searchTokens: string[], maxLength
// Strip HTML tags for text notes
if (note.type === "text") {
content = striptags(content);
+ } else if (note.type === "llmChat") {
+ // The note stores the whole conversation as a JSON blob; show the readable prose only.
+ content = extractLlmChatText(content);
+ if (!content) {
+ return "";
+ }
}
// Normalize whitespace while preserving paragraph breaks