Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: add support for assistant reply headings in ToC

Adorian Doran8baab277357b
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.spec.ts
index 3e23c169ed..1d5ce97d22 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.spec.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import { buildChatHeadings, pickActiveHeadingId, truncateForToc } from "./chat_toc.js";
+import { extractChatHeadings, pickActiveHeadingId, truncateForToc } from "./chat_toc.js";
import type { ContentBlock, StoredMessage } from "./llm_chat_types.js";
// i18next isn't initialized in unit tests, so stub `t` with a minimal interpolating
@@ -99,33 +99,49 @@ describe("truncateForToc", () => {
});
});
-describe("buildChatHeadings", () => {
+describe("extractChatHeadings", () => {
function userMessage(id: string, content: string | ContentBlock[]): StoredMessage {
return { id, role: "user", content, createdAt: "2026-01-01T00:00:00.000Z" };
}
- function assistantMessage(id: string, content: string): StoredMessage {
- return { id, role: "assistant", content, createdAt: "2026-01-01T00:00:00.000Z" };
+ function assistantMessage(id: string, content: string, type?: StoredMessage["type"]): StoredMessage {
+ return { id, role: "assistant", content, createdAt: "2026-01-01T00:00:00.000Z", type };
+ }
+ /** Build a fake chat timeline DOM out of per-message wrappers. */
+ function containerWith(...wrappers: string[]): HTMLElement {
+ const el = document.createElement("div");
+ el.innerHTML = wrappers.join("");
+ return el;
+ }
+ function messageWrapper(id: string, inner = ""): string {
+ return `<div data-message-id="${id}">${inner}</div>`;
+ }
+ function markdownContent(inner: string): string {
+ return `<div class="llm-chat-markdown">${inner}</div>`;
}
- it("emits one entry per user message, in order, skipping assistant messages", () => {
- const headings = buildChatHeadings([
+ it("emits one entry per user message, in order, skipping heading-less assistant messages", () => {
+ const headings = extractChatHeadings([
userMessage("u1", "First question"),
assistantMessage("a1", "First answer"),
userMessage("u2", "Second question")
- ]);
- expect(headings).toEqual([
+ ], containerWith(
+ messageWrapper("u1"),
+ messageWrapper("a1", markdownContent("<p>First answer</p>")),
+ messageWrapper("u2")
+ ));
+ expect(headings).toMatchObject([
{ id: "u1", level: 1, text: "First question" },
{ id: "u2", level: 1, text: "Second question" }
]);
});
it("uses the message id as the heading id so it doubles as a scroll anchor", () => {
- const [heading] = buildChatHeadings([userMessage("abc123", "Hi")]);
+ const [heading] = extractChatHeadings([userMessage("abc123", "Hi")], null);
expect(heading.id).toBe("abc123");
});
- it("escapes HTML in the message so it renders literally", () => {
- const [heading] = buildChatHeadings([userMessage("u1", "<script>alert(1)</script>")]);
+ it("escapes HTML in the user message so it renders literally", () => {
+ const [heading] = extractChatHeadings([userMessage("u1", "<script>alert(1)</script>")], null);
expect(heading.text).not.toContain("<script>");
expect(heading.text).toContain("&lt;script&gt;");
});
@@ -135,7 +151,7 @@ describe("buildChatHeadings", () => {
{ type: "image", attachmentId: "att1", mime: "image/png", title: "pic.png", url: "/x" },
{ type: "text", content: "Describe this image" }
];
- const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ const [heading] = extractChatHeadings([userMessage("u1", content)], null);
expect(heading.text).toBe("Describe this image");
});
@@ -143,7 +159,7 @@ describe("buildChatHeadings", () => {
const content: ContentBlock[] = [
{ type: "image", attachmentId: "att1", mime: "image/png", title: "diagram.png", url: "/x" }
];
- const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ const [heading] = extractChatHeadings([userMessage("u1", content)], null);
expect(heading.text).toBe("File: diagram.png");
});
@@ -151,7 +167,7 @@ describe("buildChatHeadings", () => {
const content: ContentBlock[] = [
{ type: "file", attachmentId: "att1", mime: "application/pdf", title: "report.pdf", url: "/x" }
];
- const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ const [heading] = extractChatHeadings([userMessage("u1", content)], null);
expect(heading.text).toBe("File: report.pdf");
});
@@ -159,7 +175,7 @@ describe("buildChatHeadings", () => {
const content: ContentBlock[] = [
{ type: "text_file", attachmentId: "att1", mime: "text/markdown", title: "notes.md", url: "/x" }
];
- const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ const [heading] = extractChatHeadings([userMessage("u1", content)], null);
expect(heading.text).toBe("File: notes.md");
});
@@ -169,9 +185,117 @@ describe("buildChatHeadings", () => {
{ type: "file", attachmentId: "att2", mime: "application/pdf", title: "report.pdf", url: "/y" },
{ type: "text_file", attachmentId: "att3", mime: "text/markdown", title: "notes.md", url: "/z" }
];
- const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ const [heading] = extractChatHeadings([userMessage("u1", content)], null);
expect(heading.text).toBe("File: diagram.png, report.pdf, notes.md");
});
+
+ describe("assistant reply headings", () => {
+ it("nests reply headings one level below the question (H1→2, H2→3, H3→4)", () => {
+ const headings = extractChatHeadings([
+ userMessage("u1", "Question"),
+ assistantMessage("a1", "Answer")
+ ], containerWith(
+ messageWrapper("u1"),
+ messageWrapper("a1", markdownContent("<h1>Overview</h1><p>…</p><h2>Details</h2><h3>Fine print</h3>"))
+ ));
+ expect(headings).toMatchObject([
+ { id: "u1", level: 1 },
+ { id: "a1:0", level: 2, text: "Overview" },
+ { id: "a1:1", level: 3, text: "Details" },
+ { id: "a1:2", level: 4, text: "Fine print" }
+ ]);
+ });
+
+ it("anchors each reply heading to its own element", () => {
+ const container = containerWith(
+ messageWrapper("u1"),
+ messageWrapper("a1", markdownContent("<h1>Overview</h1><h2>Details</h2>"))
+ );
+ const headings = extractChatHeadings([
+ userMessage("u1", "Question"),
+ assistantMessage("a1", "Answer")
+ ], container);
+ expect(headings[1].element?.tagName).toBe("H1");
+ expect(headings[2].element?.tagName).toBe("H2");
+ expect(headings[0].element?.dataset.messageId).toBe("u1");
+ });
+
+ it("keeps reply heading HTML as-is, without truncation", () => {
+ const longHeading = `A <strong>very</strong> long heading ${"with many words ".repeat(20)}indeed`;
+ const headings = extractChatHeadings([
+ userMessage("u1", "Q"),
+ assistantMessage("a1", "Answer")
+ ], containerWith(
+ messageWrapper("u1"),
+ messageWrapper("a1", markdownContent(`<h2>${longHeading}</h2>`))
+ ));
+ expect(headings[1].text).toBe(longHeading);
+ });
+
+ it("starts the hierarchy at level 1 when no user message precedes the reply", () => {
+ const headings = extractChatHeadings([
+ assistantMessage("a1", "Answer")
+ ], containerWith(
+ messageWrapper("a1", markdownContent("<h1>Overview</h1><h2>Details</h2>"))
+ ));
+ expect(headings).toMatchObject([
+ { id: "a1:0", level: 1, text: "Overview" },
+ { id: "a1:1", level: 2, text: "Details" }
+ ]);
+ });
+
+ it("shifts levels once a user message has appeared, even for later replies", () => {
+ const headings = extractChatHeadings([
+ assistantMessage("a1", "Preamble"),
+ userMessage("u1", "Question"),
+ assistantMessage("a2", "Answer")
+ ], containerWith(
+ messageWrapper("a1", markdownContent("<h1>Before</h1>")),
+ messageWrapper("u1"),
+ messageWrapper("a2", markdownContent("<h1>After</h1>"))
+ ));
+ expect(headings).toMatchObject([
+ { id: "a1:0", level: 1, text: "Before" },
+ { id: "u1", level: 1 },
+ { id: "a2:0", level: 2, text: "After" }
+ ]);
+ });
+
+ it("ignores headings outside the rendered markdown (e.g. tool cards)", () => {
+ const headings = extractChatHeadings([
+ userMessage("u1", "Q"),
+ assistantMessage("a1", "Answer")
+ ], containerWith(
+ messageWrapper("u1"),
+ messageWrapper("a1", `<div class="tool-card"><h1>Not a heading</h1></div>${markdownContent("<h1>Real</h1>")}`)
+ ));
+ expect(headings).toMatchObject([
+ { id: "u1", level: 1 },
+ { id: "a1:0", level: 2, text: "Real" }
+ ]);
+ });
+
+ it("skips error and thinking messages entirely", () => {
+ const headings = extractChatHeadings([
+ userMessage("u1", "Q"),
+ assistantMessage("t1", "Thinking…", "thinking"),
+ assistantMessage("e1", "Something broke", "error")
+ ], containerWith(
+ messageWrapper("u1"),
+ messageWrapper("t1", markdownContent("<h1>Thought</h1>")),
+ messageWrapper("e1", markdownContent("<h1>Oops</h1>"))
+ ));
+ expect(headings).toMatchObject([{ id: "u1", level: 1 }]);
+ });
+
+ it("skips assistant messages that are not in the DOM", () => {
+ const headings = extractChatHeadings([
+ userMessage("u1", "Q"),
+ assistantMessage("a1", "Answer")
+ ], containerWith(messageWrapper("u1")));
+ expect(headings).toMatchObject([{ id: "u1", level: 1 }]);
+ });
+ });
});
describe("pickActiveHeadingId", () => {
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
index d55726581b..09fefac915 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import type NoteContext from "../../../components/note_context.js";
import { t } from "../../../services/i18n.js";
@@ -10,25 +10,39 @@ import type { UseLlmChatReturn } from "./useLlmChat.js";
/** A single entry in the shared table-of-contents widget. */
type RawHeading = HeadingContext["headings"][number];
+/** A chat table-of-contents entry, anchored to its rendered element for scrolling and tracking. */
+export interface ChatHeading extends RawHeading {
+ element: HTMLElement | null;
+}
+
/** How far down the viewport (as a fraction of its height) the "you are here" line sits. */
const ACTIVATION_LINE_FRACTION = 0.3;
/**
- * Publishes a table of contents for an AI chat — one entry per user message — into the
- * note context, so the shared {@link TableOfContents} widget renders it exactly like the
- * text-note and PDF tables of contents. Also tracks which message is currently in view and
- * highlights the matching entry as the user scrolls.
+ * Publishes a table of contents for an AI chat into the note context, so the shared
+ * {@link TableOfContents} widget renders it exactly like the text-note and PDF tables of
+ * contents. Each user message becomes a level-1 entry (its text truncated to a short
+ * preview); headings inside assistant replies nest below it, untruncated, shifted one
+ * level down (reply H1 → level 2). Also tracks which entry is currently in view and
+ * highlights it as the user scrolls.
*/
export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | undefined) {
const { messages, scrollContainerRef } = chat;
+ const [headings, setHeadings] = useState<ChatHeading[]>([]);
const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
- const headings = useMemo(() => buildChatHeadings(messages), [messages]);
+ // Extract from the rendered DOM whenever the message list changes. Effects run after
+ // the commit, so the messages (including a just-finalized streaming reply) are in the
+ // DOM by now. Streamed-in-progress content is not in `messages` and is ignored.
+ useEffect(() => {
+ setHeadings(extractChatHeadings(messages, scrollContainerRef.current));
+ }, [messages, scrollContainerRef]);
- const scrollToHeading = useCallback((heading: RawHeading) => {
- const el = findMessageElement(scrollContainerRef.current, heading.id);
- el?.scrollIntoView({ block: "start", behavior: "smooth" });
- }, [scrollContainerRef]);
+ const scrollToHeading = useCallback((heading: ChatHeading) => {
+ if (heading.element?.isConnected) {
+ heading.element.scrollIntoView({ block: "start", behavior: "smooth" });
+ }
+ }, []);
// Scroll-spy: recompute the active heading whenever the timeline scrolls or resizes.
// Layout reads are batched into a single animation frame so a fast scroll can't queue
@@ -43,8 +57,8 @@ export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | un
const containerTop = container.getBoundingClientRect().top;
const entries: HeadingOffset[] = [];
for (const heading of headings) {
- const el = findMessageElement(container, heading.id);
- if (el) entries.push({ id: heading.id, top: el.getBoundingClientRect().top - containerTop });
+ if (!heading.element?.isConnected) continue;
+ entries.push({ id: heading.id, top: heading.element.getBoundingClientRect().top - containerTop });
}
const activationLine = container.clientHeight * ACTIVATION_LINE_FRACTION;
setActiveHeadingId(pickActiveHeadingId(entries, activationLine));
@@ -96,15 +110,49 @@ function findMessageElement(container: HTMLElement | null, messageId: string): H
return null;
}
-/** Build one table-of-contents entry per user message, in order. */
-export function buildChatHeadings(messages: StoredMessage[]): RawHeading[] {
- const headings: RawHeading[] = [];
+/** Headings inside an assistant reply's rendered markdown (excludes tool cards, citations, etc.). */
+const REPLY_HEADING_SELECTOR = [1, 2, 3, 4, 5, 6].map(n => `.llm-chat-markdown h${n}`).join(", ");
+
+/**
+ * Build the table-of-contents entries for a chat: a level-1 entry per user message
+ * (truncated preview) and, nested below it, one entry per heading found in the rendered
+ * assistant replies — untruncated, exactly like the text-note table of contents. Reply
+ * headings are shifted one level down (H1 → 2, H2 → 3, …); if no user message precedes
+ * them (e.g. an imported chat), they keep their own level so the hierarchy starts at 1.
+ */
+export function extractChatHeadings(messages: StoredMessage[], container: HTMLElement | null): ChatHeading[] {
+ const headings: ChatHeading[] = [];
+ let hasUserHeading = false;
for (const message of messages) {
- if (message.role !== "user") continue;
- const preview = truncateForToc(getMessagePreviewText(message.content));
- // The shared widget renders `text` as HTML (via RawHtml), so escape the plain
- // message text so it renders literally and can't inject markup.
- headings.push({ id: message.id, level: 1, text: escapeHtml(preview) });
+ if (message.type === "error" || message.type === "thinking") continue;
+
+ if (message.role === "user") {
+ const preview = truncateForToc(getMessagePreviewText(message.content));
+ // The shared widget renders `text` as HTML (via RawHtml), so escape the plain
+ // message text so it renders literally and can't inject markup.
+ headings.push({
+ id: message.id,
+ level: 1,
+ text: escapeHtml(preview),
+ element: findMessageElement(container, message.id)
+ });
+ hasUserHeading = true;
+ } else if (message.role === "assistant") {
+ const messageEl = findMessageElement(container, message.id);
+ if (!messageEl) continue;
+ const levelOffset = hasUserHeading ? 1 : 0;
+ let index = 0;
+ for (const headingEl of messageEl.querySelectorAll<HTMLHeadingElement>(REPLY_HEADING_SELECTOR)) {
+ headings.push({
+ id: `${message.id}:${index}`,
+ level: parseInt(headingEl.tagName.substring(1), 10) + levelOffset,
+ // Already-rendered, DOMPurify-sanitized HTML — used as-is, untruncated.
+ text: headingEl.innerHTML,
+ element: headingEl
+ });
+ index++;
+ }
+ }
}
return headings;
}