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: harden ToC context handling per review
Adorian Dorandf892bb9cb73
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.tsindex 6e2d6ed563..a8992a0476 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, useState } from "preact/hooks";+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";import type NoteContext from "../../../components/note_context.js";import { escapeHtml } from "../../../services/utils.js";@@ -68,6 +68,14 @@ export function useChatToc(chat: UseLlmChatReturn, noteContext: NoteContext | unuseEffect(() => {noteContext?.setContextData("toc", { headings, scrollToHeading, activeHeadingId });}, [noteContext, headings, scrollToHeading, activeHeadingId]);++ // Clear the published data when the chat unmounts, so the sidebar doesn't keep showing a+ // stale table of contents. Kept in its own unmount-only effect: clearing inside the publish+ // effect above would flash the list empty on every update. A ref supplies the latest+ // noteContext without re-running the effect.+ const noteContextRef = useRef(noteContext);+ noteContextRef.current = noteContext;+ useEffect(() => () => noteContextRef.current?.clearContextData("toc"), []);}interface HeadingOffset {@@ -77,9 +85,14 @@ interface HeadingOffset {}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;+ if (!container) return null;+ // Compare the parsed dataset value rather than interpolating the id into a CSS selector:+ // persisted or imported chats may carry ids with characters (quotes, backslashes, newlines)+ // that would make an attribute selector invalid and throw.+ for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {+ if (el.dataset.messageId === messageId) return el;+ }+ return null;}/** Build one table-of-contents entry per user message, in order. */@@ -209,15 +222,28 @@ function truncateToGraphemes(text: string, maxGraphemes: number): TruncationResureturn { text, truncated: false };}+// `undefined` = not yet attempted, `null` = attempted and unavailable (don't retry).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" });+ if (wordSegmenter === undefined) wordSegmenter = createSegmenter("word");return wordSegmenter;}- graphemeSegmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });+ if (graphemeSegmenter === undefined) graphemeSegmenter = createSegmenter("grapheme");return graphemeSegmenter;}++function createSegmenter(granularity: "word" | "grapheme"): Intl.Segmenter | null {+ // Instantiation can throw in environments with a partial or non-standard Intl+ // implementation; fall back to the naive split rather than crashing. The result+ // (including the null failure) is cached by the caller so this runs at most once.+ if (typeof Intl === "undefined" || typeof Intl.Segmenter === "undefined") return null;+ try {+ return new Intl.Segmenter(undefined, { granularity });+ } catch (e) {+ console.warn("Failed to initialize Intl.Segmenter:", e);+ return null;+ }+}