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
client/AI chat: refactor
Adorian Doran56468dbedc4f
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 239c1720fe..867208ee41 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -78,6 +78,10 @@ vi.mock("../widgets/collections/NoteList", () => ({ EmbeddedNoteList: embeddedNoconst iconPackPreviewComponent = vi.fn((_props: any) => null);vi.mock("../widgets/type_widgets/icon_pack/IconPackPreview", () => ({ IconPackPreview: iconPackPreviewComponent }));+const chatPreviewComponent = vi.fn((props: any): VNode<any> =>+ h("span", { class: "mock-chat-marker" }, `messages:${props.messages.length}`));+vi.mock("../widgets/type_widgets/llm_chat/ChatPreview", () => ({ default: chatPreviewComponent }));+// `addHook` is a no-op here: sanitize_content.ts registers a DOMPurify hook at// module load (pulled in transitively), which would otherwise throw against this mock.vi.mock("dompurify", () => ({ default: { sanitize: (s: string) => s, addHook: () => {} } }));@@ -115,6 +119,17 @@ function buildAttachment(row: Partial<ConstructorParameters<typeof FAttachment>[return att;}+/** An AI chat note whose stored conversation is one user message per given text. */+function buildChatNote(texts: string[]) {+ const messages = texts.map((content, i) => ({+ id: `m${i}`,+ role: "user",+ content,+ createdAt: "2026-01-01T00:00:00.000Z"+ }));+ return buildNote({ title: "Chat", type: "llmChat", content: JSON.stringify({ version: 1, messages }) });+}+beforeEach(() => {vi.clearAllMocks();isProtectedSessionAvailable.mockReturnValue(false);@@ -569,45 +584,42 @@ describe("generic FNote fallback / webView", () => {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 }- );+ it("mounts the chat preview for an AI chat note", async () => {+ const { $renderedContent } = await getRenderedContent(buildChatNote(["Ping?"]));++ expect(chatPreviewComponent).toHaveBeenCalledOnce();+ const mount = $renderedContent.find("[data-interactive-mount]");+ expect(mount.length).toBe(1);+ expect(mount.find(".mock-chat-marker").text()).toBe("messages:1");+ });- expect($renderedContent.find(".llm-chat-preview").text()).toContain("Ping?");+ it("snapshots the chat preview for a tooltip, leaving no live root behind", async () => {+ const { $renderedContent } = await getRenderedContent(buildChatNote(["Ping?"]), { tooltip: true });++ // Rendered by the same preview component as the note detail...+ expect(chatPreviewComponent).toHaveBeenCalledOnce();+ expect($renderedContent.find(".mock-chat-marker").text()).toBe("messages:1");+ // ...but unmounted afterwards: the markup survives with nothing left to dispose.expect($renderedContent.find("[data-interactive-mount]").length).toBe(0);+ disposeInteractiveContent($renderedContent);+ expect($renderedContent.find(".mock-chat-marker").length).toBe(1);});- 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 }- );+ it("caps how many messages a tooltip previews, but not the note detail", async () => {+ const messages = Array.from({ length: 25 }, (_, i) => `msg-${i}`);++ await getRenderedContent(buildChatNote(messages), { tooltip: true });+ expect(chatPreviewComponent.mock.calls[0][0].messages).toHaveLength(10);++ await getRenderedContent(buildChatNote(messages));+ expect(chatPreviewComponent.mock.calls[1][0].messages).toHaveLength(25);+ });++ it("keeps a title-only tooltip for a chat with no messages", async () => {+ const { $renderedContent } = await getRenderedContent(buildChatNote([]), { tooltip: true });- expect(empty.$renderedContent.html()).toBe("");- expect(toolOnly.$renderedContent.html()).toBe("");+ expect(chatPreviewComponent).not.toHaveBeenCalled();+ expect($renderedContent.html()).toBe("");});});diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 424dcbf2be..d390c9c43a 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -13,6 +13,7 @@ import renderText, { postProcessRichContent, renderChildrenList } from "./contenimport renderDoc from "./doc_renderer.js";import { loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";import openService from "./open.js";+import { waitForPendingRenders } from "./pending_renders.js";import protectedSessionService from "./protected_session.js";import protectedSessionHolder from "./protected_session_holder.js";import renderService from "./render.js";@@ -409,6 +410,12 @@ async function renderWebView(note: FNote, $renderedContent: JQuery<HTMLElement>)$renderedContent.append($container);}+/**+ * How many messages a tooltip previews. A hover shows a ~300px-tall scroll box, so rendering the+ * whole of a long conversation would parse hundreds of markdown bodies nobody will ever scroll to.+ */+const TOOLTIP_MAX_MESSAGES = 10;+/*** Renders a saved AI chat conversation as a read-only preview: the stored messages painted with the* same {@link ChatMessage} components as the live timeline, but with no input bar, context menu, or@@ -417,8 +424,9 @@ async function renderWebView(note: FNote, $renderedContent: JQuery<HTMLElement>)* 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.+ * A tooltip keeps only the serialized HTML of the content and never disposes it, so it would leak a+ * root per hover. It gets the same preview, snapshotted: mount it, let its async passes settle, take+ * the markup, unmount. The tooltip has no use for the interactivity it drops.*/async function renderLlmChat(note: FNote, $renderedContent: JQuery<HTMLElement>, options: RenderOptions) {const blob = await note.getBlob();@@ -438,21 +446,29 @@ 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);- if (container) {- await mountInteractiveWidget(h(ChatPreview, { messages }), container);+ if (!container) return;++ if (options.tooltip) {+ messages = messages.slice(0, TOOLTIP_MAX_MESSAGES);+ }++ await mountInteractiveWidget(h(ChatPreview, { messages }), container);++ if (options.tooltip) {+ // The chat's markdown renders through the read-only text pipeline, whose passes (mermaid,+ // math, syntax highlighting) land after the mount — snapshotting before they settle would+ // freeze half-rendered content into the tooltip.+ await waitForPendingRenders();++ const html = container.innerHTML;+ render(null, container);+ container.removeAttribute(INTERACTIVE_MOUNT_ATTR);+ container.innerHTML = html;}+$renderedContent.append($container);}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.tsdeleted file mode 100644index ffd0b1f5fb..0000000000--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.spec.ts+++ /dev/null@@ -1,68 +0,0 @@-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("<script>");- });-- 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.tsdeleted file mode 100644index 7474a0f6a5..0000000000--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_preview_html.ts+++ /dev/null@@ -1,62 +0,0 @@-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>`;-}