Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: implement a table of contents for the conversation

Adorian Doran7f5f6ba6e6ba
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
index 5fc6845e7c..7346adaec6 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
@@ -115,7 +115,7 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
const definitions: RightPanelWidgetDefinition[] = [
{
el: <TableOfContents />,
- enabled: (noteType === "text" || noteType === "doc" || isPdf || !!note?.isMarkdown()),
+ enabled: (noteType === "text" || noteType === "doc" || isPdf || noteType === "llmChat" || !!note?.isMarkdown()),
},
{
el: <PdfPages />,
diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsx
index ce4b9eea7a..a5b8e32157 100644
--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx
+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx
@@ -39,6 +39,7 @@ export default function TableOfContents() {
{((noteType === "text" && isReadOnly) || (noteType === "doc")) && <ReadOnlyTextTableOfContents />}
{noteType === "text" && !isReadOnly && <EditableTextTableOfContents />}
{noteType === "file" && noteMime === "application/pdf" && <ContextDataTableOfContents />}
+ {noteType === "llmChat" && <ContextDataTableOfContents />}
{note?.isMarkdown() && <ContextDataTableOfContents />}
</RightPanelWidget>
);
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
index e9053b94e9..b7151dd897 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -193,7 +193,7 @@ export default function ChatMessage({ message, isStreaming, onRetry }: Props) {
const hasBlockContent = Array.isArray(message.content);
return (
- <div className={`llm-chat-message-wrapper llm-chat-message-wrapper-${message.role}`} data-message-role={message.role}>
+ <div className={`llm-chat-message-wrapper llm-chat-message-wrapper-${message.role}`} data-message-role={message.role} data-message-id={message.id}>
<div className={messageClasses}>
<div className="llm-chat-message-content">
{hasBlockContent ? (
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
index 14423ee7a0..f4c373a59e 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
@@ -5,12 +5,13 @@ import { useCallback, useEffect, useRef } from "preact/hooks";
import { t } from "../../../services/i18n.js";
import { useEditorSpacedUpdate } from "../../react/hooks.js";
import { TypeWidgetProps } from "../type_widget.js";
+import { useChatToc } from "./chat_toc.js";
import ChatInputBar from "./ChatInputBar.js";
import ChatMessageList from "./ChatMessageList.js";
import type { LlmChatContent } from "./llm_chat_types.js";
import { useLlmChat } from "./useLlmChat.js";
-export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {
+export default function LlmChat({ note, noteContext }: TypeWidgetProps) {
const spacedUpdateRef = useRef<{ scheduleUpdate: () => void }>(null);
const chat = useLlmChat(
@@ -24,6 +25,9 @@ export default function LlmChat({ note, ntxId, noteContext }: TypeWidgetProps) {
chat.setChatNoteId(note?.noteId);
}, [note?.noteId, chat.setChatNoteId]);
+ // Publish a table of contents (one entry per user message) for the sidebar widget.
+ useChatToc(chat, noteContext);
+
const spacedUpdate = useEditorSpacedUpdate({
note,
noteType: "llmChat",
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
new file mode 100644
index 0000000000..118b624238
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.spec.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it } from "vitest";
+
+import { buildChatHeadings, pickActiveHeadingId, truncateForToc } from "./chat_toc.js";
+import type { ContentBlock, StoredMessage } from "./llm_chat_types.js";
+
+describe("truncateForToc", () => {
+ it("returns short text unchanged", () => {
+ expect(truncateForToc("Hello world")).toBe("Hello world");
+ });
+
+ it("returns an empty string for blank/whitespace-only input", () => {
+ expect(truncateForToc("")).toBe("");
+ expect(truncateForToc(" \n\t ")).toBe("");
+ });
+
+ it("collapses internal whitespace and newlines into single spaces", () => {
+ expect(truncateForToc("Hello \n\t world")).toBe("Hello world");
+ });
+
+ it("trims leading and trailing whitespace", () => {
+ expect(truncateForToc(" Hello world ")).toBe("Hello world");
+ });
+
+ it("keeps at most the default number of words and appends an ellipsis", () => {
+ const result = truncateForToc("one two three four five six seven eight nine");
+ expect(result).toBe("one two three four five six seven…");
+ });
+
+ it("does not append an ellipsis when the word count is exactly at the limit", () => {
+ expect(truncateForToc("one two three four five six seven")).toBe("one two three four five six seven");
+ });
+
+ it("honours a custom word limit", () => {
+ expect(truncateForToc("alpha beta gamma delta", { maxWords: 2 })).toBe("alpha beta…");
+ });
+
+ it("does not leave trailing punctuation or spaces before the ellipsis", () => {
+ // The 7th word is "seven"; the comma after it must be dropped along with the tail.
+ expect(truncateForToc("one two three four five six seven, eight nine")).toBe("one two three four five six seven…");
+ });
+
+ it("preserves punctuation that sits between kept words", () => {
+ expect(truncateForToc("Hello, world! How are you", { maxWords: 3 })).toBe("Hello, world! How…");
+ });
+
+ it("hard-caps a single very long malformed word at the default maxChars (ellipsis included)", () => {
+ const longWord = "a".repeat(1000);
+ const result = truncateForToc(longWord);
+ expect([...result]).toHaveLength(128);
+ expect(result.endsWith("…")).toBe(true);
+ expect(result.startsWith("a".repeat(127))).toBe(true);
+ });
+
+ it("respects a custom character cap", () => {
+ const result = truncateForToc("x".repeat(50), { maxChars: 10 });
+ expect([...result]).toHaveLength(10);
+ expect(result).toBe(`${"x".repeat(9)}…`);
+ });
+
+ it("never exceeds maxChars even when both word and char limits fire", () => {
+ const words = Array.from({ length: 20 }, () => "z".repeat(40)).join(" ");
+ const result = truncateForToc(words, { maxWords: 7, maxChars: 100 });
+ expect([...result].length).toBeLessThanOrEqual(100);
+ expect(result.endsWith("…")).toBe(true);
+ });
+
+ describe("cross-culture word segmentation", () => {
+ it("counts Chinese words without relying on spaces", () => {
+ // "你好世界" has no spaces; Intl.Segmenter still splits it into words, so the
+ // ellipsis proves a genuine word boundary was found rather than a whitespace split.
+ const result = truncateForToc("你好世界再见朋友们今天天气很好", { maxWords: 3 });
+ expect(result.endsWith("…")).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+ });
+
+ it("handles German text with punctuation", () => {
+ expect(truncateForToc("Größe und Straße sind Wörter", { maxWords: 3 })).toBe("Größe und Straße…");
+ });
+
+ it("keeps Romanian diacritics intact", () => {
+ expect(truncateForToc("Această propoziție are cuvinte", { maxWords: 2 })).toBe("Această propoziție…");
+ });
+
+ it("does not split multi-code-point emoji when capping characters", () => {
+ // A family emoji is several code points joined by ZWJ but one grapheme; the cap
+ // must not slice through it and leave a broken cluster.
+ const emoji = "👨‍👩‍👧‍👦";
+ const result = truncateForToc(emoji.repeat(300), { maxWords: 100, maxChars: 5 });
+ // 4 whole emoji + the ellipsis; no lone surrogate fragments.
+ expect(result).toBe(`${emoji.repeat(4)}…`);
+ });
+ });
+});
+
+describe("buildChatHeadings", () => {
+ 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" };
+ }
+
+ it("emits one entry per user message, in order, skipping assistant messages", () => {
+ const headings = buildChatHeadings([
+ userMessage("u1", "First question"),
+ assistantMessage("a1", "First answer"),
+ userMessage("u2", "Second question")
+ ]);
+ expect(headings).toEqual([
+ { 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")]);
+ expect(heading.id).toBe("abc123");
+ });
+
+ it("escapes HTML in the message so it renders literally", () => {
+ const [heading] = buildChatHeadings([userMessage("u1", "<script>alert(1)</script>")]);
+ expect(heading.text).not.toContain("<script>");
+ expect(heading.text).toContain("&lt;script&gt;");
+ });
+
+ it("extracts the text from block-shaped content", () => {
+ const content: ContentBlock[] = [
+ { type: "image", attachmentId: "att1", mime: "image/png", title: "pic.png", url: "/x" },
+ { type: "text", content: "Describe this image" }
+ ];
+ const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ expect(heading.text).toBe("Describe this image");
+ });
+
+ it("falls back to an attachment title for image-only messages", () => {
+ const content: ContentBlock[] = [
+ { type: "image", attachmentId: "att1", mime: "image/png", title: "diagram.png", url: "/x" }
+ ];
+ const [heading] = buildChatHeadings([userMessage("u1", content)]);
+ expect(heading.text).toBe("diagram.png");
+ });
+});
+
+describe("pickActiveHeadingId", () => {
+ it("returns null when there are no entries", () => {
+ expect(pickActiveHeadingId([], 100)).toBeNull();
+ });
+
+ it("highlights the first entry when nothing has been scrolled past the line", () => {
+ const entries = [
+ { id: "a", top: 300 },
+ { id: "b", top: 600 }
+ ];
+ expect(pickActiveHeadingId(entries, 100)).toBe("a");
+ });
+
+ it("highlights the last entry whose top is at or above the activation line", () => {
+ const entries = [
+ { id: "a", top: -200 },
+ { id: "b", top: 50 },
+ { id: "c", top: 400 }
+ ];
+ expect(pickActiveHeadingId(entries, 100)).toBe("b");
+ });
+
+ it("treats an entry exactly on the line as scrolled past", () => {
+ const entries = [
+ { id: "a", top: -50 },
+ { id: "b", top: 100 }
+ ];
+ expect(pickActiveHeadingId(entries, 100)).toBe("b");
+ });
+
+ it("highlights the final entry when the timeline is scrolled to the bottom", () => {
+ const entries = [
+ { id: "a", top: -900 },
+ { id: "b", top: -600 },
+ { id: "c", top: -100 }
+ ];
+ expect(pickActiveHeadingId(entries, 100)).toBe("c");
+ });
+});
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
new file mode 100644
index 0000000000..6e2d6ed563
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_toc.ts
@@ -0,0 +1,223 @@
+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
+
+import type NoteContext from "../../../components/note_context.js";
+import { escapeHtml } from "../../../services/utils.js";
+import type { HeadingContext } from "../../sidebar/TableOfContents.js";
+import { type ContentBlock, getMessageText, type StoredMessage } from "./llm_chat_types.js";
+import type { UseLlmChatReturn } from "./useLlmChat.js";
+
+/** A single entry in the shared table-of-contents widget. */
+type RawHeading = HeadingContext["headings"][number];
+
+/** 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.
+ */
+export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | undefined) {
+ const { messages, scrollContainerRef } = chat;
+ const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
+
+ const headings = useMemo(() => buildChatHeadings(messages), [messages]);
+
+ const scrollToHeading = useCallback((heading: RawHeading) => {
+ const el = findMessageElement(scrollContainerRef.current, heading.id);
+ el?.scrollIntoView({ block: "start", behavior: "smooth" });
+ }, [scrollContainerRef]);
+
+ // 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
+ // a backlog of reflows.
+ useEffect(() => {
+ const container = scrollContainerRef.current;
+ if (!container) return;
+
+ let rafId: number | null = null;
+ const recompute = () => {
+ rafId = null;
+ 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 });
+ }
+ const activationLine = container.clientHeight * ACTIVATION_LINE_FRACTION;
+ setActiveHeadingId(pickActiveHeadingId(entries, activationLine));
+ };
+ const schedule = () => {
+ if (rafId == null) rafId = requestAnimationFrame(recompute);
+ };
+
+ recompute();
+ container.addEventListener("scroll", schedule, { passive: true });
+ const resizeObserver = typeof ResizeObserver !== "undefined" ? new ResizeObserver(schedule) : null;
+ resizeObserver?.observe(container);
+
+ return () => {
+ container.removeEventListener("scroll", schedule);
+ resizeObserver?.disconnect();
+ if (rafId != null) cancelAnimationFrame(rafId);
+ };
+ }, [headings, scrollContainerRef]);
+
+ // Publish to the note context so the shared sidebar widget can consume it.
+ useEffect(() => {
+ noteContext?.setContextData("toc", { headings, scrollToHeading, activeHeadingId });
+ }, [noteContext, headings, scrollToHeading, activeHeadingId]);
+}
+
+interface HeadingOffset {
+ id: string;
+ /** Distance (px) of the message's top edge below the scroll container's top edge. */
+ top: number;
+}
+
+function findMessageElement(container: HTMLElement | null, messageId: string): HTMLElement | null {
+ // Message IDs are generated by randomString() (alphanumeric), so they are safe to
+ // interpolate straight into an attribute selector.
+ return container?.querySelector<HTMLElement>(`[data-message-id="${messageId}"]`) ?? null;
+}
+
+/** Build one table-of-contents entry per user message, in order. */
+export function buildChatHeadings(messages: StoredMessage[]): RawHeading[] {
+ const headings: RawHeading[] = [];
+ 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) });
+ }
+ return headings;
+}
+
+/** Pick the entry whose section the reader is currently in: the last one scrolled past the activation line. */
+export function pickActiveHeadingId(entries: HeadingOffset[], activationLine: number): string | null {
+ if (entries.length === 0) return null;
+ // Default to the first entry so that when nothing has been scrolled past yet
+ // (all messages sit below the line) the top entry is highlighted.
+ let active = entries[0].id;
+ for (const entry of entries) {
+ if (entry.top <= activationLine) active = entry.id;
+ }
+ return active;
+}
+
+/**
+ * The text used to preview a user message in the table of contents. Falls back to an
+ * attachment's title for messages that carry only an image or file and no prose.
+ */
+function getMessagePreviewText(content: string | ContentBlock[]): string {
+ const text = getMessageText(content);
+ if (text.trim()) return text;
+ if (Array.isArray(content)) {
+ for (const block of content) {
+ if ((block.type === "image" || block.type === "file" || block.type === "text_file") && block.title) {
+ return block.title;
+ }
+ }
+ }
+ return "";
+}
+
+const ELLIPSIS = "…";
+
+export interface TruncateOptions {
+ /** Maximum number of words to keep. */
+ maxWords?: number;
+ /** Hard cap on the character (grapheme) count of the whole result, ellipsis included. */
+ maxChars?: number;
+}
+
+/**
+ * Produce a short, single-line preview of a chat message for the table of contents.
+ *
+ * Collapses whitespace, keeps at most `maxWords` words, then hard-caps the result at
+ * `maxChars` characters as a defence against a single very long / malformed "word".
+ * Word and character boundaries are found with `Intl.Segmenter`, so it behaves correctly
+ * across cultures — scripts without spaces (e.g. Chinese, Japanese), combining marks, and
+ * multi-code-point emoji — rather than naively splitting on spaces or UTF-16 units.
+ */
+export function truncateForToc(text: string, { maxWords = 7, maxChars = 128 }: TruncateOptions = {}): string {
+ // Collapse every run of whitespace (including newlines) into a single space for a one-line label.
+ const normalized = text.replace(/\s+/g, " ").trim();
+ if (!normalized) return "";
+
+ const word = truncateToWords(normalized, maxWords);
+ // Grapheme-cap the (possibly word-truncated) text. When an ellipsis will be appended,
+ // leave room for it so the final string never exceeds `maxChars`.
+ let truncated = word.truncated;
+ const initialCap = truncateToGraphemes(word.text, maxChars);
+ truncated = truncated || initialCap.truncated;
+ let result = truncated ? truncateToGraphemes(initialCap.text, maxChars - 1).text : initialCap.text;
+
+ result = result.trimEnd();
+ return truncated ? result + ELLIPSIS : result;
+}
+
+interface TruncationResult {
+ text: string;
+ truncated: boolean;
+}
+
+function truncateToWords(text: string, maxWords: number): TruncationResult {
+ if (maxWords <= 0) return { text: "", truncated: text.length > 0 };
+
+ const segmenter = getSegmenter("word");
+ if (!segmenter) {
+ // Fallback for environments without Intl.Segmenter: naive whitespace split.
+ const parts = text.split(" ");
+ if (parts.length <= maxWords) return { text, truncated: false };
+ return { text: parts.slice(0, maxWords).join(" "), truncated: true };
+ }
+
+ let wordCount = 0;
+ let cutIndex = text.length;
+ for (const { segment, index, isWordLike } of segmenter.segment(text)) {
+ if (!isWordLike) continue;
+ wordCount++;
+ if (wordCount === maxWords) {
+ // Remember where the last kept word ends, dropping any trailing punctuation/space.
+ cutIndex = index + segment.length;
+ } else if (wordCount > maxWords) {
+ return { text: text.slice(0, cutIndex), truncated: true };
+ }
+ }
+ return { text, truncated: false };
+}
+
+function truncateToGraphemes(text: string, maxGraphemes: number): TruncationResult {
+ if (maxGraphemes <= 0) return { text: "", truncated: text.length > 0 };
+
+ const segmenter = getSegmenter("grapheme");
+ if (!segmenter) {
+ // Fallback: count code points so surrogate pairs are at least kept intact.
+ const codePoints = [...text];
+ if (codePoints.length <= maxGraphemes) return { text, truncated: false };
+ return { text: codePoints.slice(0, maxGraphemes).join(""), truncated: true };
+ }
+
+ let count = 0;
+ for (const { index } of segmenter.segment(text)) {
+ if (count === maxGraphemes) return { text: text.slice(0, index), truncated: true };
+ count++;
+ }
+ return { text, truncated: false };
+}
+
+let wordSegmenter: Intl.Segmenter | null | undefined;
+let graphemeSegmenter: Intl.Segmenter | null | undefined;
+
+function getSegmenter(granularity: "word" | "grapheme"): Intl.Segmenter | null {
+ if (typeof Intl === "undefined" || typeof Intl.Segmenter === "undefined") return null;
+ if (granularity === "word") {
+ wordSegmenter ??= new Intl.Segmenter(undefined, { granularity: "word" });
+ return wordSegmenter;
+ }
+ graphemeSegmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });
+ return graphemeSegmenter;
+}