Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: add text highlight support for replies

Adorian Dorane46e69fc9e5c
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index 8b3b245894..e9452d6b79 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -14,6 +14,7 @@ import treeService from "../services/tree.js";
import utils from "../services/utils.js";
import { ReactWrappedWidget } from "../widgets/basic_widget.js";
import type { HeadingContext } from "../widgets/sidebar/TableOfContents.js";
+import type { ChatHighlightsContext } from "../widgets/type_widgets/llm_chat/chat_highlights.js";
import appContext, { type EventData, type EventListener } from "./app_context.js";
import Component from "./component.js";
@@ -39,6 +40,7 @@ const READ_ONLY_CAPABLE_TYPES: string[] = [
export interface NoteContextDataMap {
toc: HeadingContext;
+ chatHighlights: ChatHighlightsContext;
pdfPages: {
totalPages: number;
currentPage: number;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ed20cf5e87..2836c41ef2 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2071,6 +2071,10 @@
"retry": "Retry",
"scroll_to_bottom": "Scroll to latest",
"toc_file": "File: {{name}}",
+ "highlights_title": "Highlights ({{count}})",
+ "highlights_empty": "No highlights yet. Select text in a message and choose \"Highlight\".",
+ "highlight_add": "Highlight",
+ "highlight_remove": "Remove highlight",
"attach_file": "Attach image, PDF, or text file",
"remove_attachment": "Remove attachment",
"attachment_upload_failed": "Failed to upload \"{{name}}\".",
diff --git a/apps/client/src/widgets/sidebar/ChatHighlightsList.css b/apps/client/src/widgets/sidebar/ChatHighlightsList.css
new file mode 100644
index 0000000000..563ba200f3
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/ChatHighlightsList.css
@@ -0,0 +1,40 @@
+.chat-highlights-list ol {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.chat-highlights-list li {
+ display: flex;
+ align-items: center;
+ gap: 0.25em;
+ padding: 0.25em 0.4em;
+ border-radius: 4px;
+ cursor: pointer;
+}
+
+.chat-highlights-list li:hover {
+ background-color: var(--hover-item-background-color);
+}
+
+.chat-highlights-list .chat-highlight-text {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.chat-highlights-list .chat-highlight-remove {
+ flex-shrink: 0;
+ opacity: 0;
+}
+
+.chat-highlights-list li:hover .chat-highlight-remove,
+.chat-highlights-list .chat-highlight-remove:focus-visible {
+ opacity: 1;
+}
+
+.chat-highlights-list .no-highlights {
+ padding: 0.4em;
+ opacity: 0.7;
+}
diff --git a/apps/client/src/widgets/sidebar/ChatHighlightsList.tsx b/apps/client/src/widgets/sidebar/ChatHighlightsList.tsx
new file mode 100644
index 0000000000..5370c80e38
--- /dev/null
+++ b/apps/client/src/widgets/sidebar/ChatHighlightsList.tsx
@@ -0,0 +1,42 @@
+import "./ChatHighlightsList.css";
+
+import { t } from "../../services/i18n";
+import ActionButton from "../react/ActionButton";
+import { useGetContextData } from "../react/hooks";
+import RightPanelWidget from "./RightPanelWidget";
+
+/**
+ * Sidebar list of the user's highlights in the active AI chat. The data (and the scroll/remove
+ * actions) are published by {@link useChatHighlights} into the note context; this widget only renders.
+ */
+export default function ChatHighlightsList() {
+ const data = useGetContextData("chatHighlights");
+ const highlights = data?.highlights ?? [];
+
+ return (
+ <RightPanelWidget id="chat-highlights" title={t("llm_chat.highlights_title", { count: highlights.length })} grow>
+ <span className="chat-highlights-list">
+ {highlights.length > 0 ? (
+ <ol>
+ {highlights.map(highlight => (
+ <li key={highlight.id} onClick={() => data?.scrollToHighlight(highlight.id)}>
+ <span className="chat-highlight-text">{highlight.text}</span>
+ <ActionButton
+ className="chat-highlight-remove"
+ icon="bx bx-x"
+ text={t("llm_chat.highlight_remove")}
+ onClick={e => {
+ e.stopPropagation();
+ data?.removeHighlight(highlight.id);
+ }}
+ />
+ </li>
+ ))}
+ </ol>
+ ) : (
+ <div className="no-highlights">{t("llm_chat.highlights_empty")}</div>
+ )}
+ </span>
+ </RightPanelWidget>
+ );
+}
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
index 7346adaec6..b2cb66ab1a 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.tsx
@@ -14,18 +14,19 @@ import { DEFAULT_GUTTER_SIZE } from "../../services/resizer";
import { isStandalone } from "../../services/utils";
import ActionButton from "../react/ActionButton";
import Button from "../react/Button";
-import { useActiveNoteContext, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";
+import { useActiveNoteContext, useGetContextData, useLegacyWidget, useNoteProperty, useTriliumEvent, useTriliumOptionBool, useTriliumOptionJson } from "../react/hooks";
import LazyComponent from "../react/LazyComponent";
import NoItems from "../react/NoItems";
import { PaneMode, usePaneMode, usePeekDismiss } from "../react/peek_pane";
import LegacyRightPanelWidget from "../right_panel_widget";
+import ChatHighlightsList from "./ChatHighlightsList";
import HighlightsList from "./HighlightsList";
import PdfAnnotations from "./pdf/PdfAnnotations";
import PdfAttachments from "./pdf/PdfAttachments";
import PdfLayers from "./pdf/PdfLayers";
import PdfPages from "./pdf/PdfPages";
-import RightPanePeekButton from "./RightPanePeekButton";
import RightPanelWidget from "./RightPanelWidget";
+import RightPanePeekButton from "./RightPanePeekButton";
import TableOfContents from "./TableOfContents";
const MIN_WIDTH_PERCENT = 5;
@@ -107,6 +108,9 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
const noteType = useNoteProperty(note, "type");
const noteMime = useNoteProperty(note, "mime");
const [ highlightsList ] = useTriliumOptionJson<string[]>("highlightsList");
+ // Published by the LLM chat; drives the chat highlights widget's visibility (only shown once
+ // the chat has at least one highlight).
+ const chatHighlights = useGetContextData("chatHighlights");
// Subscribe to the AI toggle so the LLM chat is added/removed reactively without a page reload.
const [ aiEnabled ] = useTriliumOptionBool("aiEnabled");
const isPdf = noteType === "file" && noteMime === "application/pdf";
@@ -137,6 +141,10 @@ function useItems(rightPaneVisible: boolean, widgetsByParent: WidgetsByParent) {
el: <HighlightsList />,
enabled: noteType === "text" && highlightsList.length > 0,
},
+ {
+ el: <ChatHighlightsList />,
+ enabled: noteType === "llmChat" && (chatHighlights?.highlights.length ?? 0) > 0,
+ },
{
// Loaded lazily because the chat pulls in the whole LLM + CKEditor graph,
// which users without the LLM experimental feature should never download.
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 f4c373a59e..765999ca0e 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
@@ -5,6 +5,7 @@ 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 { useChatHighlights } from "./chat_highlights.js";
import { useChatToc } from "./chat_toc.js";
import ChatInputBar from "./ChatInputBar.js";
import ChatMessageList from "./ChatMessageList.js";
@@ -28,6 +29,9 @@ export default function LlmChat({ note, noteContext }: TypeWidgetProps) {
// Publish a table of contents (one entry per user message) for the sidebar widget.
useChatToc(chat, noteContext);
+ // Paint user-created highlights over the replies and publish them for the sidebar widget.
+ useChatHighlights(chat, noteContext);
+
const spacedUpdate = useEditorSpacedUpdate({
note,
noteType: "llmChat",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css
new file mode 100644
index 0000000000..b5729dc5df
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.css
@@ -0,0 +1,6 @@
+/* Painted over user-created highlight ranges via the CSS Custom Highlight API (see chat_highlights.ts).
+ The name matches the single registry entry ("chat-highlight"), so only chat highlight ranges use it. */
+::highlight(chat-highlight) {
+ background-color: var(--chat-highlight-background-color, #ffe066);
+ color: var(--chat-highlight-text-color, #1a1a1a);
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts
new file mode 100644
index 0000000000..840482ae0b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts
@@ -0,0 +1,252 @@
+import "./chat_highlights.css";
+
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+
+import type NoteContext from "../../../components/note_context.js";
+import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";
+import { t } from "../../../services/i18n.js";
+import { randomString } from "../../../services/utils.js";
+import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";
+import type { HighlightAnchor, StoredMessage } from "./llm_chat_types.js";
+import type { UseLlmChatReturn } from "./useLlmChat.js";
+
+/** A highlight surfaced in the sidebar list. */
+export interface ChatHighlightItem {
+ id: string;
+ messageId: string;
+ /** The highlighted prose, shown as the list entry's label. */
+ text: string;
+}
+
+/** Context data published for the {@link ChatHighlightsList} sidebar widget. */
+export interface ChatHighlightsContext {
+ highlights: ChatHighlightItem[];
+ scrollToHighlight(id: string): void;
+ removeHighlight(id: string): void;
+}
+
+/** The single CSS Custom Highlight registry entry all chat highlights paint through. */
+const HIGHLIGHT_NAME = "chat-highlight";
+
+/**
+ * Wires up user-created highlights for an AI chat: painting stored highlights over the rendered
+ * prose, a right-click menu to add and remove them, and publishing the list to the note context so
+ * the shared sidebar widget can display it — mirroring {@link useChatToc}.
+ *
+ * Highlights are painted with the CSS Custom Highlight API rather than by wrapping text in elements,
+ * so nothing is injected into the Preact-owned message DOM. Because that paints over live `Range`s
+ * (which go stale when a message re-renders), the ranges are rebuilt from the stored anchors on every
+ * message change.
+ */
+export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteContext | undefined) {
+ const { messages, isStreaming, scrollContainerRef } = chat;
+ const [highlightItems, setHighlightItems] = useState<ChatHighlightItem[]>([]);
+
+ // Latest values for the imperative event handler and callbacks, so they never read stale state.
+ const messagesRef = useRef(messages);
+ messagesRef.current = messages;
+ const isStreamingRef = useRef(isStreaming);
+ isStreamingRef.current = isStreaming;
+ const setMessagesRef = useRef(chat.setMessages);
+ setMessagesRef.current = chat.setMessages;
+
+ // Live registry entry + the resolved ranges behind the currently painted highlights, keyed by
+ // anchor id (used for hit-testing on right-click).
+ const highlightRef = useRef<Highlight | null>(null);
+ const rangesRef = useRef(new Map<string, { range: Range; messageId: string }>());
+
+ const paint = useCallback((rangeById: Map<string, { range: Range; messageId: string }>) => {
+ const highlight = ensureHighlight(highlightRef);
+ if (!highlight) return;
+ highlight.clear();
+ for (const { range } of rangeById.values()) highlight.add(range);
+ }, []);
+
+ // Rebuild ranges from the stored anchors and repaint. A layout effect so painting settles in the
+ // same frame the messages render — no flash. The stream keeps `messages` stable, so this doesn't
+ // run per token.
+ const recompute = useCallback(() => {
+ const container = scrollContainerRef.current;
+ if (!container) return;
+
+ const rangeById = new Map<string, { range: Range; messageId: string }>();
+ const items: ChatHighlightItem[] = [];
+ for (const message of messagesRef.current) {
+ if (!message.highlights?.length) continue;
+ const root = findMessageContentRoot(container, message.id);
+ if (!root) continue;
+ for (const anchor of message.highlights) {
+ const range = resolveAnchorRange(root, anchor);
+ if (!range) continue; // orphaned (e.g. regenerated message) — drop cleanly, never mis-paint
+ rangeById.set(anchor.id, { range, messageId: message.id });
+ items.push({ id: anchor.id, messageId: message.id, text: anchor.quotedText });
+ }
+ }
+
+ rangesRef.current = rangeById;
+ paint(rangeById);
+ setHighlightItems(items);
+ }, [scrollContainerRef, paint]);
+
+ useLayoutEffect(() => recompute(), [messages, recompute]);
+
+ // Drop the registry entry on unmount so a switched-away chat leaves no paint behind.
+ useEffect(() => () => {
+ highlightRef.current = null;
+ if (isHighlightApiAvailable()) CSS.highlights.delete(HIGHLIGHT_NAME);
+ }, []);
+
+ const addHighlight = useCallback((messageId: string, built: Omit<HighlightAnchor, "id">) => {
+ const anchor: HighlightAnchor = { id: randomString(), ...built };
+ setMessagesRef.current(messagesRef.current.map(message =>
+ message.id === messageId
+ ? { ...message, highlights: [...(message.highlights ?? []), anchor] }
+ : message
+ ));
+ }, []);
+
+ const removeHighlight = useCallback((anchorId: string) => {
+ setMessagesRef.current(messagesRef.current.map(message => {
+ if (!message.highlights?.some(h => h.id === anchorId)) return message;
+ const remaining = message.highlights.filter(h => h.id !== anchorId);
+ return { ...message, highlights: remaining.length ? remaining : undefined };
+ }));
+ }, []);
+
+ const scrollToHighlight = useCallback((anchorId: string) => {
+ const container = scrollContainerRef.current;
+ if (!container) return;
+ const located = findAnchor(messagesRef.current, anchorId);
+ if (!located) return;
+ const root = findMessageContentRoot(container, located.messageId);
+ if (!root) return;
+ const range = resolveAnchorRange(root, located.anchor);
+ const element = range && nearestElement(range.startContainer);
+ element?.scrollIntoView({ block: "center", behavior: "smooth" });
+ }, [scrollContainerRef]);
+
+ // Right-click: remove when the click lands on an existing highlight, else offer to highlight a
+ // prose selection. Attached to the timeline; both paths bail (leaving the native menu) when there's
+ // nothing to do, so ordinary right-clicks are untouched.
+ useEffect(() => {
+ const container = scrollContainerRef.current;
+ if (!container) return;
+
+ const onContextMenu = (e: MouseEvent) => {
+ if (isStreamingRef.current) return; // mutating messages mid-stream would race the finalized reply
+ const wrapper = (e.target as HTMLElement | null)?.closest<HTMLElement>("[data-message-id]");
+ const messageId = wrapper?.dataset.messageId;
+ const root = wrapper?.querySelector<HTMLElement>(".llm-chat-message-content");
+ if (!messageId || !root) return; // thinking/error messages carry no id → not highlightable
+
+ const hitId = highlightAtPoint(rangesRef.current, messageId, e.clientX, e.clientY);
+ if (hitId) {
+ e.preventDefault();
+ showMenu(e, t("llm_chat.highlight_remove"), "bx bx-eraser", () => removeHighlight(hitId));
+ return;
+ }
+
+ const range = selectionRangeWithin(container.ownerDocument.getSelection(), root);
+ const built = range && createAnchorFromSelection(root, range);
+ if (!built) return;
+ e.preventDefault();
+ showMenu(e, t("llm_chat.highlight_add"), "bx bx-highlight", () => addHighlight(messageId, built));
+ };
+
+ container.addEventListener("contextmenu", onContextMenu);
+ return () => container.removeEventListener("contextmenu", onContextMenu);
+ }, [scrollContainerRef, addHighlight, removeHighlight]);
+
+ // Publish the list for the sidebar widget; clear it on unmount so no stale list lingers.
+ useEffect(() => {
+ noteContext?.setContextData("chatHighlights", { highlights: highlightItems, scrollToHighlight, removeHighlight });
+ }, [noteContext, highlightItems, scrollToHighlight, removeHighlight]);
+
+ const noteContextRef = useRef(noteContext);
+ noteContextRef.current = noteContext;
+ useEffect(() => () => noteContextRef.current?.clearContextData("chatHighlights"), []);
+}
+
+function isHighlightApiAvailable(): boolean {
+ return typeof Highlight !== "undefined" && typeof CSS !== "undefined" && !!CSS.highlights;
+}
+
+function ensureHighlight(ref: { current: Highlight | null }): Highlight | null {
+ if (ref.current) return ref.current;
+ if (!isHighlightApiAvailable()) return null;
+ const highlight = new Highlight();
+ ref.current = highlight;
+ CSS.highlights.set(HIGHLIGHT_NAME, highlight);
+ return highlight;
+}
+
+function findMessageContentRoot(container: HTMLElement, messageId: string): HTMLElement | null {
+ // Match on the parsed dataset value rather than an attribute selector: persisted/imported chats
+ // may carry ids with characters that would make a selector invalid and throw.
+ for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {
+ if (el.dataset.messageId === messageId) return el.querySelector<HTMLElement>(".llm-chat-message-content");
+ }
+ return null;
+}
+
+function findAnchor(messages: StoredMessage[], anchorId: string): { anchor: HighlightAnchor; messageId: string } | null {
+ for (const message of messages) {
+ const anchor = message.highlights?.find(h => h.id === anchorId);
+ if (anchor) return { anchor, messageId: message.id };
+ }
+ return null;
+}
+
+/** The selection's range if it is non-empty and fully contained within `root`, else null. */
+function selectionRangeWithin(selection: Selection | null, root: HTMLElement): Range | null {
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;
+ const range = selection.getRangeAt(0);
+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null;
+ return range;
+}
+
+/** The id of the smallest highlight (of `messageId`) painted under the given viewport point, if any. */
+function highlightAtPoint(ranges: Map<string, { range: Range; messageId: string }>, messageId: string, x: number, y: number): string | null {
+ const caret = caretFromPoint(document, x, y);
+ if (!caret) return null;
+
+ let bestId: string | null = null;
+ let bestLength = Infinity;
+ for (const [id, { range, messageId: owner }] of ranges) {
+ if (owner !== messageId) continue;
+ try {
+ if (!range.isPointInRange(caret.node, caret.offset)) continue;
+ } catch {
+ continue; // point in a different document subtree
+ }
+ const length = range.toString().length;
+ if (length < bestLength) {
+ bestLength = length;
+ bestId = id;
+ }
+ }
+ return bestId;
+}
+
+function caretFromPoint(doc: Document, x: number, y: number): { node: Node; offset: number } | null {
+ if (typeof doc.caretPositionFromPoint === "function") {
+ const pos = doc.caretPositionFromPoint(x, y);
+ return pos?.offsetNode ? { node: pos.offsetNode, offset: pos.offset } : null;
+ }
+ // Older Chromium/Electron only expose the WebKit-prefixed variant.
+ const legacy = (doc as unknown as { caretRangeFromPoint?: (x: number, y: number) => Range | null }).caretRangeFromPoint;
+ if (typeof legacy === "function") {
+ const range = legacy.call(doc, x, y);
+ return range ? { node: range.startContainer, offset: range.startOffset } : null;
+ }
+ return null;
+}
+
+function nearestElement(node: Node): HTMLElement | null {
+ return node instanceof HTMLElement ? node : node.parentElement;
+}
+
+function showMenu(e: MouseEvent, title: string, uiIcon: string, handler: () => void) {
+ const items: MenuItem<unknown>[] = [{ title, uiIcon, handler }];
+ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.spec.ts
new file mode 100644
index 0000000000..e993002c51
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.spec.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+
+import { buildProseProjection, resolveAnchorIndices, resolveAnchorRange } from "./chat_highlights_anchor.js";
+import type { HighlightAnchor } from "./llm_chat_types.js";
+
+function anchor(partial: Partial<HighlightAnchor>): HighlightAnchor {
+ return { id: "a", start: 0, end: 0, quotedText: "", ...partial };
+}
+
+/** Build a message content root (`.llm-chat-message-content`) wrapping rendered markdown. */
+function contentRoot(markdownHtml: string, extraHtml = ""): HTMLElement {
+ const root = document.createElement("div");
+ root.className = "llm-chat-message-content";
+ root.innerHTML = `<div class="llm-chat-markdown">${markdownHtml}</div>${extraHtml}`;
+ return root;
+}
+
+describe("resolveAnchorIndices", () => {
+ const text = "the quick brown fox jumps over the lazy dog";
+
+ it("uses the stored offsets when they still frame the quoted text", () => {
+ expect(resolveAnchorIndices(text, anchor({ start: 4, end: 9, quotedText: "quick" }))).toEqual({ start: 4, end: 9 });
+ });
+
+ it("relocates when the offsets have drifted but the text is unique", () => {
+ // Offsets point at the wrong place; there is only one "brown" so it relocates unambiguously.
+ expect(resolveAnchorIndices(text, anchor({ start: 0, end: 5, quotedText: "brown" }))).toEqual({ start: 10, end: 15 });
+ });
+
+ it("disambiguates repeated text by surrounding context", () => {
+ const repeated = "pick the red apple then pick the red cherry";
+ const first = resolveAnchorIndices(repeated, anchor({ start: -1, end: -1, quotedText: "red", prefix: "pick the ", suffix: " apple" }));
+ const second = resolveAnchorIndices(repeated, anchor({ start: -1, end: -1, quotedText: "red", prefix: "pick the ", suffix: " cherry" }));
+ expect(repeated.slice(first?.start, first?.end)).toBe("red");
+ expect(repeated.slice(second?.start, second?.end)).toBe("red");
+ expect(first?.start).toBe(9);
+ expect(second?.start).toBe(33);
+ });
+
+ it("returns null when the quoted text is gone (e.g. a regenerated message)", () => {
+ expect(resolveAnchorIndices(text, anchor({ start: 4, end: 9, quotedText: "elephant" }))).toBeNull();
+ });
+
+ it("returns null for an empty quote", () => {
+ expect(resolveAnchorIndices(text, anchor({ quotedText: "" }))).toBeNull();
+ });
+});
+
+describe("buildProseProjection", () => {
+ it("concatenates prose while skipping code, math, and non-markdown text", () => {
+ const root = contentRoot(
+ `<p>Hello <code>skip()</code> world</p><pre>ignored block</pre><p>bye</p>`,
+ `<div class="tool-card">tool noise</div>`
+ );
+ expect(buildProseProjection(root).text).toBe("Hello worldbye");
+ });
+
+ it("produces a range that reads back the quoted prose", () => {
+ const root = contentRoot(`<p>alpha beta gamma</p>`);
+ const range = resolveAnchorRange(root, anchor({ start: 6, end: 10, quotedText: "beta" }));
+ expect(range?.toString()).toBe("beta");
+ });
+
+ it("relocates a drifted anchor to the right prose via its quote", () => {
+ const root = contentRoot(`<p>alpha beta gamma</p>`);
+ const range = resolveAnchorRange(root, anchor({ start: 999, end: 1000, quotedText: "gamma" }));
+ expect(range?.toString()).toBe("gamma");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts
new file mode 100644
index 0000000000..100ad173d6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights_anchor.ts
@@ -0,0 +1,207 @@
+import type { HighlightAnchor } from "./llm_chat_types.js";
+
+/**
+ * Anchoring for chat highlights: turning a live text selection into a durable {@link HighlightAnchor},
+ * and resolving a stored anchor back into a DOM {@link Range} at render time.
+ *
+ * A chat message's text is immutable once its turn completes, so highlights are anchored to that
+ * text rather than to the rendered DOM (which the markdown pipeline regenerates on every render).
+ * Anchoring works over a *prose projection* of a message: the concatenation of the message's rendered
+ * markdown text, skipping non-prose (code blocks, math, diagrams, tool cards, images) so that
+ * asynchronously-rendered or opaque content can never shift or corrupt an offset.
+ */
+
+/** Only text inside rendered markdown counts as highlightable prose. */
+const PROSE_CONTAINER_SELECTOR = ".llm-chat-markdown";
+/** Non-prose subtrees skipped within the markdown: code, math (async KaTeX), diagrams. */
+const NON_PROSE_SELECTOR = "pre, code, .math-tex, .katex, .ck-math-tex, .mermaid, svg";
+/** How much surrounding prose to store as disambiguating context on each side of a highlight. */
+const CONTEXT_LENGTH = 24;
+
+/** A run of highlightable prose contributed by a single DOM text node. */
+interface ProseSegment {
+ node: Text;
+ /** Offset of this run's first character within the projection string. */
+ start: number;
+ length: number;
+}
+
+/** The flattened prose of a message plus the mapping back to its DOM text nodes. */
+export interface ProseProjection {
+ text: string;
+ segments: ProseSegment[];
+}
+
+/**
+ * Build a {@link HighlightAnchor} (minus its id) from a live selection within a message's content
+ * root. Returns `null` when the selection is empty or covers no prose (e.g. only a code block or
+ * image) — the boundaries are snapped to the nearest prose so a selection that spills into
+ * non-prose is clipped rather than rejected outright.
+ */
+export function createAnchorFromSelection(root: HTMLElement, range: Range): Omit<HighlightAnchor, "id"> | null {
+ if (range.collapsed) return null;
+
+ const projection = buildProseProjection(root);
+ if (!projection.text) return null;
+
+ const start = boundaryToIndex(projection, range.startContainer, range.startOffset, "start");
+ const end = boundaryToIndex(projection, range.endContainer, range.endOffset, "end");
+ if (start == null || end == null || end <= start) return null;
+
+ const quotedText = projection.text.slice(start, end);
+ if (!quotedText.trim()) return null;
+
+ return {
+ start,
+ end,
+ quotedText,
+ prefix: projection.text.slice(Math.max(0, start - CONTEXT_LENGTH), start),
+ suffix: projection.text.slice(end, end + CONTEXT_LENGTH)
+ };
+}
+
+/** Resolve a stored anchor to a live {@link Range} within `root`, or `null` if it can't be located. */
+export function resolveAnchorRange(root: HTMLElement, anchor: HighlightAnchor): Range | null {
+ const projection = buildProseProjection(root);
+ const indices = resolveAnchorIndices(projection.text, anchor);
+ if (!indices) return null;
+ return rangeFromProjection(root, projection.segments, indices.start, indices.end);
+}
+
+/**
+ * Locate an anchor within a message's flattened prose. Pure string logic (no DOM), so the tricky
+ * part — surviving render-pipeline drift — is unit-testable in isolation.
+ *
+ * Fast path: if the stored offsets still frame exactly the quoted text, use them as-is. Otherwise
+ * the offsets have drifted (e.g. a KaTeX/markdown upgrade re-rendered an earlier block), so relocate
+ * by searching for the quoted text, disambiguating repeats by surrounding context and, as a final
+ * tie-breaker, proximity to the original offset. Returns `null` when the text is gone entirely
+ * (a regenerated message), so the caller cleanly drops the highlight rather than mis-painting.
+ */
+export function resolveAnchorIndices(text: string, anchor: HighlightAnchor): { start: number; end: number } | null {
+ const { start, end, quotedText, prefix = "", suffix = "" } = anchor;
+ if (!quotedText) return null;
+
+ if (start >= 0 && end <= text.length && start < end && text.slice(start, end) === quotedText) {
+ return { start, end };
+ }
+
+ const matches = findAllOccurrences(text, quotedText);
+ if (matches.length === 0) return null;
+ if (matches.length === 1) return { start: matches[0], end: matches[0] + quotedText.length };
+
+ let best = matches[0];
+ let bestScore = -1;
+ for (const match of matches) {
+ const score = contextScore(text, match, quotedText.length, prefix, suffix);
+ const isBetter = score > bestScore || (score === bestScore && Math.abs(match - start) < Math.abs(best - start));
+ if (isBetter) {
+ best = match;
+ bestScore = score;
+ }
+ }
+ return { start: best, end: best + quotedText.length };
+}
+
+/** Concatenate a message content root's prose text, recording where each text node lands. */
+export function buildProseProjection(root: HTMLElement): ProseProjection {
+ const segments: ProseSegment[] = [];
+ let text = "";
+
+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const textNode = node as Text;
+ if (!isProseTextNode(textNode)) continue;
+ segments.push({ node: textNode, start: text.length, length: textNode.data.length });
+ text += textNode.data;
+ }
+
+ return { text, segments };
+}
+
+function isProseTextNode(node: Text): boolean {
+ const parent = node.parentElement;
+ if (!parent) return false;
+ if (!parent.closest(PROSE_CONTAINER_SELECTOR)) return false;
+ if (parent.closest(NON_PROSE_SELECTOR)) return false;
+ return true;
+}
+
+/** Map a DOM selection boundary onto a projection offset, snapping off-prose points to the nearest prose. */
+function boundaryToIndex(projection: ProseProjection, node: Node, offset: number, snap: "start" | "end"): number | null {
+ const { segments, text } = projection;
+ if (segments.length === 0) return null;
+
+ for (const seg of segments) {
+ if (seg.node === node) return seg.start + Math.min(offset, seg.length);
+ }
+
+ // The boundary sits on an element edge or inside excluded content: snap in document order.
+ let prevEnd = 0;
+ for (const seg of segments) {
+ if (pointCompare(node, offset, seg.node, 0) <= 0) {
+ return snap === "start" ? seg.start : prevEnd;
+ }
+ prevEnd = seg.start + seg.length;
+ }
+ return snap === "start" ? text.length : prevEnd;
+}
+
+/** Build a DOM range spanning projection offsets `[start, end)`. */
+function rangeFromProjection(root: HTMLElement, segments: ProseSegment[], start: number, end: number): Range | null {
+ const startPoint = locateOffset(segments, start);
+ const endPoint = locateOffset(segments, end);
+ if (!startPoint || !endPoint) return null;
+
+ const range = root.ownerDocument.createRange();
+ range.setStart(startPoint.node, startPoint.offset);
+ range.setEnd(endPoint.node, endPoint.offset);
+ return range;
+}
+
+function locateOffset(segments: ProseSegment[], index: number): { node: Text; offset: number } | null {
+ for (const seg of segments) {
+ if (index <= seg.start + seg.length) {
+ return { node: seg.node, offset: Math.max(0, index - seg.start) };
+ }
+ }
+ const last = segments[segments.length - 1];
+ return last ? { node: last.node, offset: last.length } : null;
+}
+
+/** Standard comparator (-1 / 0 / +1) for two DOM points, offsets included. */
+function pointCompare(aNode: Node, aOffset: number, bNode: Node, bOffset: number): number {
+ const range = aNode.ownerDocument?.createRange();
+ if (!range) return 0;
+ range.setStart(aNode, aOffset);
+ // comparePoint returns -1 if b is before the (collapsed-at-a) range, +1 if after.
+ const cmp = range.comparePoint(bNode, bOffset);
+ return cmp === 0 ? 0 : -cmp;
+}
+
+function findAllOccurrences(haystack: string, needle: string): number[] {
+ const indices: number[] = [];
+ for (let from = haystack.indexOf(needle); from !== -1; from = haystack.indexOf(needle, from + 1)) {
+ indices.push(from);
+ }
+ return indices;
+}
+
+/** How many characters of stored context still match around a candidate match — higher is a better fit. */
+function contextScore(text: string, matchStart: number, matchLength: number, prefix: string, suffix: string): number {
+ const before = text.slice(0, matchStart);
+ const after = text.slice(matchStart + matchLength);
+ return commonSuffixLength(before, prefix) + commonPrefixLength(after, suffix);
+}
+
+function commonSuffixLength(a: string, b: string): number {
+ let n = 0;
+ while (n < a.length && n < b.length && a[a.length - 1 - n] === b[b.length - 1 - n]) n++;
+ return n;
+}
+
+function commonPrefixLength(a: string, b: string): number {
+ let n = 0;
+ while (n < a.length && n < b.length && a[n] === b[n]) n++;
+ return n;
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
index e27069ccb0..2531f7fa66 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
@@ -98,6 +98,29 @@ export function getMessageToolCalls(message: StoredMessage): ToolCall[] {
return [];
}
+/**
+ * A user-created highlight over a stretch of a message's rendered prose.
+ *
+ * The message text never changes once a turn completes, so a highlight is anchored to that
+ * text rather than to the volatile rendered DOM. `start`/`end` are character offsets into the
+ * message's flattened prose (the fast, exact primary locator); `quotedText` plus its
+ * surrounding context is the robust fallback that revalidates — and, if the render pipeline
+ * ever shifts the offsets, relocates — the highlight. See {@link resolveAnchorIndices}.
+ */
+export interface HighlightAnchor {
+ id: string;
+ /** Character offset of the highlight's start in the message's flattened prose. */
+ start: number;
+ /** Character offset of the highlight's end (exclusive) in the message's flattened prose. */
+ end: number;
+ /** The highlighted prose itself — used to validate/relocate the offsets. */
+ quotedText: string;
+ /** A few characters of prose immediately before the highlight, to disambiguate repeats. */
+ prefix?: string;
+ /** A few characters of prose immediately after the highlight, to disambiguate repeats. */
+ suffix?: string;
+}
+
export interface StoredMessage {
id: string;
role: "user" | "assistant" | "system";
@@ -109,6 +132,8 @@ export interface StoredMessage {
type?: MessageType;
/** Token usage for this response */
usage?: LlmUsage;
+ /** User-created text highlights over this message's rendered prose. */
+ highlights?: HighlightAnchor[];
}
export interface LlmChatContent {