Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: add preview support for note tooltips

Adorian Doran73462e739f32
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 5b9782fb8f..239c1720fe 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -568,6 +568,47 @@ describe("generic FNote fallback / webView", () => {
expect(noSrc.$renderedContent.find(".note-detail-web-view").length).toBe(0);
expect(noSrc.$renderedContent.hasClass("no-preview")).toBe(true);
});
+
+ it("renders an AI chat in a tooltip as a static preview, without mounting the widget", async () => {
+ const content = JSON.stringify({
+ version: 1,
+ messages: [{ id: "m1", role: "user", content: "Ping?", createdAt: "2026-01-01T00:00:00.000Z" }]
+ });
+ const { $renderedContent } = await getRenderedContent(
+ buildNote({ title: "Chat", type: "llmChat", content }),
+ { tooltip: true }
+ );
+
+ expect($renderedContent.find(".llm-chat-preview").text()).toContain("Ping?");
+ expect($renderedContent.find("[data-interactive-mount]").length).toBe(0);
+ });
+
+ it("keeps a title-only tooltip for an AI chat with nothing to preview", async () => {
+ const empty = await getRenderedContent(
+ buildNote({ title: "Chat", type: "llmChat", content: JSON.stringify({ version: 1, messages: [] }) }),
+ { tooltip: true }
+ );
+ // Only tool calls: no text to show, so the preview stays empty rather than rendering a blank bubble.
+ const toolOnly = await getRenderedContent(
+ buildNote({
+ title: "Chat",
+ type: "llmChat",
+ content: JSON.stringify({
+ version: 1,
+ messages: [{
+ id: "m1",
+ role: "assistant",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ content: [{ type: "tool_call", toolCall: { id: "t1", toolName: "search_notes", input: {} } }]
+ }]
+ })
+ }),
+ { tooltip: true }
+ );
+
+ expect(empty.$renderedContent.html()).toBe("");
+ expect(toolOnly.$renderedContent.html()).toBe("");
+ });
});
describe("interactive content disposal", () => {
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 0c884ffc18..424dcbf2be 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -109,8 +109,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNo
$renderedContent.append($("<div>").append("<div>This note is protected and to access it you need to enter password.</div>").append("<br/>").append($button));
} else if (type === "webView" && options.interactive && !options.tooltip && entity instanceof FNote && entity.hasLabel("webViewSrc")) {
await renderWebView(entity, $renderedContent);
- } else if (type === "llmChat" && !options.tooltip && entity instanceof FNote) {
- await renderLlmChat(entity, $renderedContent);
+ } else if (type === "llmChat" && entity instanceof FNote) {
+ await renderLlmChat(entity, $renderedContent, options);
} else if (entity instanceof FNote) {
$renderedContent.addClass("no-preview");
$renderedContent.append(
@@ -416,8 +416,11 @@ async function renderWebView(note: FNote, $renderedContent: JQuery<HTMLElement>)
* effects), so the embedding caller must tear it down via {@link disposeInteractiveContent} — the
* collection tiles that show these previews already do. Loaded lazily so the chat widget code is only
* pulled in when a chat note is previewed.
+ *
+ * Tooltips get a static string rendering instead: they keep only the serialized HTML of the content
+ * and never dispose it, so a mounted preview would leak a Preact root per hover.
*/
-async function renderLlmChat(note: FNote, $renderedContent: JQuery<HTMLElement>) {
+async function renderLlmChat(note: FNote, $renderedContent: JQuery<HTMLElement>, options: RenderOptions) {
const blob = await note.getBlob();
const source = blob?.content ?? "";
@@ -435,6 +438,15 @@ async function renderLlmChat(note: FNote, $renderedContent: JQuery<HTMLElement>)
}
if (messages.length === 0) return;
+ if (options.tooltip) {
+ const { renderChatPreviewHtml } = await import("../widgets/type_widgets/llm_chat/chat_preview_html");
+ const html = renderChatPreviewHtml(messages);
+ if (html) {
+ $renderedContent.append($('<div class="note-detail-llm-chat-preview">').html(html));
+ }
+ return;
+ }
+
const ChatPreview = (await import("../widgets/type_widgets/llm_chat/ChatPreview")).default;
const $container = $('<div class="note-detail-llm-chat-preview">');
const container = $container.get(0);
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.spec.ts
new file mode 100644
index 0000000000..ffd0b1f5fb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.spec.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+
+import { renderChatPreviewHtml } from "./chat_preview_html.js";
+import type { StoredMessage } from "./llm_chat_types.js";
+
+function message(overrides: Partial<StoredMessage> = {}): StoredMessage {
+ return {
+ id: "m1",
+ role: "user",
+ content: "hello",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ ...overrides
+ };
+}
+
+describe("renderChatPreviewHtml", () => {
+ it("renders each message as a role-classed bubble with its markdown", () => {
+ const html = renderChatPreviewHtml([
+ message({ id: "m1", role: "user", content: "What is **42**?" }),
+ message({ id: "m2", role: "assistant", content: [{ type: "text", content: "The answer." }] })
+ ]);
+
+ expect(html).toContain("llm-chat-message-wrapper-user");
+ expect(html).toContain("llm-chat-message-wrapper-assistant");
+ expect(html).toContain("<strong>42</strong>");
+ expect(html).toContain("The answer.");
+ });
+
+ it("renders an error message as a caution admonition with escaped text", () => {
+ const html = renderChatPreviewHtml([
+ message({ role: "assistant", type: "error", content: "failed <script>" })
+ ]);
+
+ expect(html).toContain('class="admonition caution llm-chat-error"');
+ expect(html).not.toContain("<script>");
+ expect(html).toContain("&lt;script&gt;");
+ });
+
+ it("skips thinking messages and messages with no text (tool calls, attachments only)", () => {
+ const html = renderChatPreviewHtml([
+ message({ id: "m1", type: "thinking", content: "pondering" }),
+ message({
+ id: "m2",
+ role: "assistant",
+ content: [{ type: "tool_call", toolCall: { id: "t1", toolName: "search_notes", input: {} } }]
+ }),
+ message({ id: "m3", role: "user", content: "kept" })
+ ]);
+
+ expect(html).not.toContain("pondering");
+ expect(html).not.toContain("search_notes");
+ expect(html).toContain("kept");
+ expect(html.match(/llm-chat-message-wrapper /g)).toHaveLength(1);
+ });
+
+ it("caps the number of previewed messages", () => {
+ const messages = Array.from({ length: 25 }, (_, i) => message({ id: `m${i}`, content: `msg-${i}` }));
+ const html = renderChatPreviewHtml(messages);
+
+ expect(html).toContain("msg-9");
+ expect(html).not.toContain("msg-10");
+ });
+
+ it("returns an empty string when nothing is worth previewing", () => {
+ expect(renderChatPreviewHtml([])).toBe("");
+ expect(renderChatPreviewHtml([message({ content: " " })])).toBe("");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.ts
new file mode 100644
index 0000000000..7474a0f6a5
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.ts
@@ -0,0 +1,62 @@
+import "../markdown/MarkdownCommons.css";
+import "./ChatMessage.css";
+import "./ChatPreview.css";
+
+import { escapeHtml } from "../../../services/utils.js";
+import { renderMarkdown } from "./chat_markdown.js";
+import { getMessageText, type StoredMessage } from "./llm_chat_types.js";
+
+/**
+ * Renders a stored conversation as a static HTML string, for previews that keep only the serialized
+ * markup and never get a chance to unmount a component — currently the note tooltip, which stringifies
+ * the rendered content and hands it to Bootstrap. Mounting {@link ChatPreview} there would leave a live
+ * Preact root (and its event subscriptions) behind on every hover, so this path trades interactivity
+ * for a plain string: the message bubbles and their markdown, no tool cards, attachments, citations or
+ * footers. Class names mirror {@link ChatMessage} so the same stylesheets apply.
+ *
+ * Returns an empty string when there is nothing worth showing, letting the caller fall back to a
+ * title-only preview.
+ */
+export function renderChatPreviewHtml(messages: StoredMessage[]): string {
+ const bubbles = messages
+ .slice(0, MAX_PREVIEW_MESSAGES)
+ .map(renderMessage)
+ .filter(Boolean);
+
+ if (!bubbles.length) {
+ return "";
+ }
+
+ return `<div class="llm-chat-preview">${bubbles.join("")}</div>`;
+}
+
+/**
+ * A preview is capped so hovering a long conversation doesn't parse hundreds of markdown messages,
+ * almost all of them scrolled out of the tooltip's viewport anyway.
+ */
+const MAX_PREVIEW_MESSAGES = 10;
+
+function renderMessage(message: StoredMessage): string {
+ // Thinking blocks are collapsed by default in the live timeline; in a preview they would only
+ // push the actual conversation out of view.
+ if (message.type === "thinking") {
+ return "";
+ }
+
+ const text = getMessageText(message.content);
+ if (!text.trim()) {
+ // Nothing textual to show — e.g. a message carrying only tool calls or attachments.
+ return "";
+ }
+
+ const wrapperRole = message.role === "user" ? "user" : "assistant";
+ const body = message.type === "error"
+ ? `<div class="admonition caution llm-chat-error">${escapeHtml(text)}</div>`
+ : `<div class="llm-chat-message llm-chat-message-${wrapperRole}">
+ <div class="llm-chat-message-content">
+ <div class="ck-content use-tn-links llm-chat-markdown">${renderMarkdown(text)}</div>
+ </div>
+ </div>`;
+
+ return `<div class="llm-chat-message-wrapper llm-chat-message-wrapper-${wrapperRole}">${body}</div>`;
+}