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 Doran6202d2c741d9
diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsxindex 6351f5c885..444185d4bb 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx@@ -12,6 +12,7 @@ import ActionButton from "../react/ActionButton.js";import Dropdown from "../react/Dropdown.js";import { FormDropdownDivider, FormListItem } from "../react/FormList.js";import { useActiveNoteContext, useNote, useNoteProperty, useSpacedUpdate } from "../react/hooks.js";+import { useChatContextMenu } from "../type_widgets/llm_chat/chat_context_menu.js";import { useChatHighlights } from "../type_widgets/llm_chat/chat_highlights.js";import ChatInputBar from "../type_widgets/llm_chat/ChatInputBar.js";import ChatMessageList from "../type_widgets/llm_chat/ChatMessageList.js";@@ -55,10 +56,13 @@ export default function SidebarChat() {const chatRef = useRef(chat);chatRef.current = chat;- // Enable highlighting (painting + right-click Add/Remove/Copy) in the sidebar chat. No note context- // is passed: the sidebar chat is itself the right pane, so there's no slot for the highlights list —- // the highlights live in the messages only.- useChatHighlights(chat, undefined);+ // Enable highlighting (painting + right-click add/remove) in the sidebar chat. No note context is+ // passed: the sidebar chat is itself the right pane, so there's no slot for the highlights list —+ // the highlights live in the messages only. Save-to-sub-note is likewise unavailable (no parent).+ const highlights = useChatHighlights(chat, undefined);++ // Right-click menu over the timeline, with highlights contributing their add/remove items.+ useChatContextMenu({ chat, noteContext: undefined, contextMenuItems: highlights.highlightMenuItems });// Save directly via server.put using the string noteId.// This avoids the FNote dependency that useEditorSpacedUpdate requires.diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsxindex db0a5b48a9..b97798eb44 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 { useChatContextMenu } from "./chat_context_menu.js";import { useChatHighlights } from "./chat_highlights.js";import { useChatMessageJumps } from "./chat_message_jump.js";import { useChatToc } from "./chat_toc.js";@@ -31,7 +32,10 @@ export default function LlmChat({ note, noteContext }: TypeWidgetProps) {useChatToc(chat, noteContext);// Paint user-created highlights over the replies and publish them for the sidebar widget.- useChatHighlights(chat, noteContext);+ const highlights = useChatHighlights(chat, noteContext);++ // Right-click menu over the timeline, with highlights contributing their add/remove items.+ useChatContextMenu({ chat, noteContext, contextMenuItems: highlights.highlightMenuItems });// Make the "message ID …" links in submitted quotes jump to the referenced message.useChatMessageJumps(chat.scrollContainerRef);diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.tsnew file mode 100644index 0000000000..d12c5a1e3e--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_context_menu.ts@@ -0,0 +1,170 @@+import { useCallback, useEffect, useRef } from "preact/hooks";++import type NoteContext from "../../../components/note_context.js";+import contextMenu, { type MenuItem } from "../../../menus/context_menu.js";+import dialog from "../../../services/dialog.js";+import { t } from "../../../services/i18n.js";+import toast from "../../../services/toast.js";+import { canCopyMessage, copyMessageToClipboard } from "./chat_copy.js";+import { canDeleteMessage, removeMessage } from "./chat_delete.js";+import { buildQuoteMarkdown } from "./chat_quote.js";+import { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";+import { getMessageText } from "./llm_chat_types.js";+import type { UseLlmChatReturn } from "./useLlmChat.js";++/** The right-clicked message and its surrounding state, passed to command contributors. */+export interface ChatMessageMenuContext {+ /** Id of the message the click landed on. */+ messageId: string;+ /** The message's rendered content root (`.llm-chat-message-content`). */+ root: HTMLElement;+ /** The non-empty selection within `root`, or null. */+ selectionRange: Range | null;+ /** Whether a reply is currently streaming. */+ streaming: boolean;+ clientX: number;+ clientY: number;+}++/** Builds extra context-menu items for the right-clicked message (e.g. highlight add/remove). */+export type ChatContextMenuItemsProvider = (ctx: ChatMessageMenuContext) => MenuItem<unknown>[];++/** Options for {@link useChatContextMenu}. An object so new fields can be added without changing callers. */+export interface ChatContextMenuOptions {+ chat: UseLlmChatReturn;+ /** The chat's note context (note chats); undefined for the right-pane sidebar chat. */+ noteContext: NoteContext | undefined;+ /** Builds extra items to add to the message's context menu (e.g. highlight add/remove). */+ contextMenuItems: ChatContextMenuItemsProvider;+}++/**+ * The right-click menu over an AI chat's message timeline. Owns the single `contextmenu` listener and+ * builds the menu for the message under the cursor: with a text selection — Copy and Quote; with none+ * — Copy message, Save to a sub-note (note chats only) and Delete. `contextMenuItems` lets another+ * concern (currently highlights) inject its own items next to the selection commands. Bails to the+ * native menu when nothing applies.+ *+ * Preventing the default menu drops the browser's own Copy, so we provide a rich Copy here. Copy stays+ * available while a reply streams; the message-mutating commands (highlight add/remove, delete) are+ * suppressed then.+ */+export function useChatContextMenu({ chat, noteContext, contextMenuItems }: ChatContextMenuOptions) {+ const { scrollContainerRef } = chat;++ // Latest values for the imperative event handler, so it never reads stale state.+ const messagesRef = useRef(chat.messages);+ messagesRef.current = chat.messages;+ const isStreamingRef = useRef(chat.isStreaming);+ isStreamingRef.current = chat.isStreaming;+ const setMessagesRef = useRef(chat.setMessages);+ setMessagesRef.current = chat.setMessages;+ const appendToInputRef = useRef(chat.appendToInput);+ appendToInputRef.current = chat.appendToInput;+ // Present for note chats (a real note in a tab), undefined for the right-pane sidebar chat —+ // gates "Save to sub-note" (note chats only) and is the new note's parent.+ const noteContextRef = useRef(noteContext);+ noteContextRef.current = noteContext;++ const confirmAndDeleteMessage = useCallback(async (messageId: string) => {+ if (await dialog.confirm(t("llm_chat.delete_message_confirm"))) {+ setMessagesRef.current(removeMessage(messagesRef.current, messageId));+ }+ }, []);++ useEffect(() => {+ const container = scrollContainerRef.current;+ if (!container) return;++ const onContextMenu = (e: MouseEvent) => {+ 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 → nothing to offer++ const streaming = isStreamingRef.current;+ const selectionRange = selectionRangeWithin(container.ownerDocument.getSelection(), root);+ const hasSelection = !!selectionRange?.toString().trim();+ const message = messagesRef.current.find(m => m.id === messageId);+ const messageMarkdown = message ? getMessageText(message.content) : "";+ const parentNotePath = noteContextRef.current?.notePath;++ const items: MenuItem<unknown>[] = [];++ // Copy the live selection as rich text: execCommand serializes the selected DOM to both+ // text/html and text/plain (what the native menu we suppressed would have done).+ if (hasSelection) {+ items.push({ title: t("llm_chat.copy"), uiIcon: "bx bx-copy", handler: copySelection });+ }++ // Injected commands (highlight add/remove) sit next to the selection commands.+ items.push(...contextMenuItems({ messageId, root, selectionRange, streaming, clientX: e.clientX, clientY: e.clientY }));++ // Quote the selection into the reply input. Suppressed while streaming — the input is+ // read-only then. Text is captured now (the menu can clear the live selection before the+ // handler runs).+ const quotedText = !streaming ? selectionRange?.toString() : undefined;+ if (quotedText?.trim()) {+ items.push({+ title: t("llm_chat.quote_selection"),+ uiIcon: "bx bxs-quote-alt-left",+ handler: () => appendToInputRef.current(buildQuoteMarkdown(quotedText, messageId))+ });+ }++ // Whole-message commands, offered when there's no selection (a selection means the+ // selection commands above apply). Rendered from the message's markdown source so math,+ // mermaid, and code survive intact.+ if (canCopyMessage(hasSelection, messageMarkdown)) {+ items.push({+ title: t("llm_chat.copy_message"),+ uiIcon: "bx bx-copy",+ handler: () => copyMessageToClipboard(messageMarkdown)+ });+ }+ if (parentNotePath && canSaveToSubNote(parentNotePath, hasSelection, messageMarkdown)) {+ items.push({+ title: t("llm_chat.save_to_subnote"),+ uiIcon: "bx bx-save",+ handler: () => void saveMessageToSubNote(parentNotePath, messageMarkdown)+ });+ }+ if (canDeleteMessage(hasSelection, message, streaming)) {+ items.push({+ title: t("llm_chat.delete_message"),+ uiIcon: "bx bx-trash",+ handler: () => void confirmAndDeleteMessage(messageId)+ });+ }++ if (items.length === 0) return; // nothing to do → leave the native menu+ e.preventDefault();+ showMenu(e, items);+ };++ container.addEventListener("contextmenu", onContextMenu);+ return () => container.removeEventListener("contextmenu", onContextMenu);+ }, [scrollContainerRef, contextMenuItems, confirmAndDeleteMessage]);+}++/** 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;+}++function showMenu(e: MouseEvent, items: MenuItem<unknown>[]) {+ void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });+}++/** Copy the current selection as rich text. The menu opens on mousedown, so the selection is still live. */+function copySelection() {+ const ok = document.execCommand("copy");+ if (ok) {+ toast.showMessage(t("clipboard.copy_success"));+ } else {+ toast.showError(t("clipboard.copy_failed"));+ }+}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.tsindex 41dde14cc7..2d1b8e1ca0 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_highlights.ts@@ -3,17 +3,11 @@ 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 dialog from "../../../services/dialog.js";import { t } from "../../../services/i18n.js";-import toast from "../../../services/toast.js";import { randomString } from "../../../services/utils.js";-import { canCopyMessage, copyMessageToClipboard } from "./chat_copy.js";-import { canDeleteMessage, removeMessage } from "./chat_delete.js";+import type { ChatContextMenuItemsProvider } from "./chat_context_menu.js";import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";-import { buildQuoteMarkdown } from "./chat_quote.js";-import { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";-import { getMessageText, type HighlightAnchor } from "./llm_chat_types.js";+import type { HighlightAnchor } from "./llm_chat_types.js";import type { UseLlmChatReturn } from "./useLlmChat.js";/** A highlight surfaced in the sidebar list. */@@ -31,6 +25,12 @@ export interface ChatHighlightsContext {removeHighlight(id: string): void;}+/** What {@link useChatHighlights} exposes to the shared chat context menu. */+export interface ChatHighlights {+ /** Highlight items for the right-clicked message: remove over an existing highlight, else add for a selection. */+ highlightMenuItems: ChatContextMenuItemsProvider;+}+/** The single CSS Custom Highlight registry entry all chat highlights paint through. */const HIGHLIGHT_NAME = "chat-highlight";@@ -44,32 +44,24 @@ const activeRangeMaps = new Set<{ current: RangeMap }>();let sharedHighlight: Highlight | null = null;/**- * 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}.+ * Wires up user-created highlights for an AI chat: painting stored highlights over the rendered prose,+ * contributing add/remove items to the shared chat context menu, and publishing the list to the note+ * context so the 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;+export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteContext | undefined): ChatHighlights {+ const { messages, scrollContainerRef } = chat;const [highlightItems, setHighlightItems] = useState<ChatHighlightItem[]>([]);- // Latest values for the imperative event handler and callbacks, so they never read stale state.+ // Latest values for the imperative 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;- const appendToInputRef = useRef(chat.appendToInput);- appendToInputRef.current = chat.appendToInput;- // Present for note chats (a real note in a tab), undefined for the right-pane sidebar chat —- // used to gate "Save to sub-note" (note chats only) and as the new note's parent.- const noteContextRef = useRef(noteContext);- noteContextRef.current = noteContext;// The resolved ranges behind this chat's currently painted highlights, keyed by anchor id (used// for hit-testing on right-click and for scroll-to). Registered in the module-level set so the@@ -126,12 +118,6 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte}));}, []);- const confirmAndDeleteMessage = useCallback(async (messageId: string) => {- if (await dialog.confirm(t("llm_chat.delete_message_confirm"))) {- setMessagesRef.current(removeMessage(messagesRef.current, messageId));- }- }, []);-const scrollToHighlight = useCallback((anchorId: string) => {// Reuse the range resolved by the most recent recompute rather than re-walking the DOM; every// listed highlight has a cached entry (the list is built from the same resolved set).@@ -140,89 +126,21 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConteelement?.scrollIntoView({ block: "center", behavior: "smooth" });}, []);- // Right-click menu over the timeline. With a text selection: Copy, Quote, and Add/Remove- // highlight. With no selection: Copy the whole message, Save it to a sub-note (note chats only),- // and Delete it. Because preventing the default menu drops the browser's own Copy, we provide it- // here. Bails (leaving the native menu) when there's nothing to offer. Copy stays available while- // a reply streams; the message-mutating add/remove/delete are suppressed then.- useEffect(() => {- const container = scrollContainerRef.current;- if (!container) return;-- const onContextMenu = (e: MouseEvent) => {- 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 → nothing to offer-- const streaming = isStreamingRef.current;- const hitId = streaming ? null : highlightAtPoint(rangesRef.current, messageId, e.clientX, e.clientY);- const selectionRange = selectionRangeWithin(container.ownerDocument.getSelection(), root);- const built = !streaming && selectionRange ? createAnchorFromSelection(root, selectionRange) : null;-- const items: MenuItem<unknown>[] = [];- // Copy the live selection as rich text: execCommand serializes the selected DOM to both- // text/html and text/plain (what the native menu we suppressed would have done).- if (selectionRange?.toString().trim()) {- items.push({ title: t("llm_chat.copy"), uiIcon: "bx bx-copy", handler: copySelection });- }- if (hitId) {- items.push({ title: t("llm_chat.highlight_remove"), uiIcon: "bx bx-eraser", handler: () => removeHighlight(hitId) });- } else if (built) {- items.push({ title: t("llm_chat.highlight_add"), uiIcon: "bx bx-highlight", handler: () => addHighlight(messageId, built) });- }-- // Quote the selection into the reply input. Disabled while streaming — the input is- // read-only then, so there's nowhere to write it. Text is captured now (the menu can- // clear the live selection before the handler runs).- const quotedText = !streaming ? selectionRange?.toString() : undefined;- if (quotedText?.trim()) {- items.push({- title: t("llm_chat.quote_selection"),- uiIcon: "bx bxs-quote-alt-left",- handler: () => appendToInputRef.current(buildQuoteMarkdown(quotedText, messageId))- });- }-- // Save the whole message as a child note and open it in this tab. Note chats only — the- // right-pane sidebar chat has no note to parent under (no noteContext). Rendered from the- // message's markdown source so math, mermaid, and code survive intact. Offered on the- // message surface only when there's no text selection: with a selection the selection- // commands above apply, and a whole-message save would then be confusing.- const parentNotePath = noteContextRef.current?.notePath;- const hasSelection = !!selectionRange?.toString().trim();- const message = messagesRef.current.find(m => m.id === messageId);- const messageMarkdown = message ? getMessageText(message.content) : "";- if (canCopyMessage(hasSelection, messageMarkdown)) {- items.push({- title: t("llm_chat.copy_message"),- uiIcon: "bx bx-copy",- handler: () => copyMessageToClipboard(messageMarkdown)- });- }- if (parentNotePath && canSaveToSubNote(parentNotePath, hasSelection, messageMarkdown)) {- items.push({- title: t("llm_chat.save_to_subnote"),- uiIcon: "bx bx-save",- handler: () => void saveMessageToSubNote(parentNotePath, messageMarkdown)- });- }- if (canDeleteMessage(hasSelection, message, streaming)) {- items.push({- title: t("llm_chat.delete_message"),- uiIcon: "bx bx-trash",- handler: () => void confirmAndDeleteMessage(messageId)- });- }-- if (items.length === 0) return; // nothing to do → leave the native menu- e.preventDefault();- showMenu(e, items);- };-- container.addEventListener("contextmenu", onContextMenu);- return () => container.removeEventListener("contextmenu", onContextMenu);- }, [scrollContainerRef, addHighlight, removeHighlight, confirmAndDeleteMessage]);+ // Contribute the highlight commands to the chat context menu: Remove over an existing highlight,+ // else Highlight for a prose selection. Both mutate the message, so they're suppressed while a+ // reply streams.+ const highlightMenuItems = useCallback<ChatContextMenuItemsProvider>((ctx) => {+ if (ctx.streaming) return [];+ const hitId = highlightAtPoint(rangesRef.current, ctx.messageId, ctx.clientX, ctx.clientY);+ if (hitId) {+ return [{ title: t("llm_chat.highlight_remove"), uiIcon: "bx bx-eraser", handler: () => removeHighlight(hitId) }];+ }+ const built = ctx.selectionRange ? createAnchorFromSelection(ctx.root, ctx.selectionRange) : null;+ if (built) {+ return [{ title: t("llm_chat.highlight_add"), uiIcon: "bx bx-highlight", handler: () => addHighlight(ctx.messageId, built) }];+ }+ return [];+ }, [addHighlight, removeHighlight]);// Publish the list for the sidebar widget.useEffect(() => {@@ -233,6 +151,8 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte// doesn't keep showing a stale list. Kept separate from the publish effect above — clearing there// would flash the list empty on every update.useEffect(() => () => noteContext?.clearContextData("chatHighlights"), [noteContext]);++ return { highlightMenuItems };}function isHighlightApiAvailable(): boolean {@@ -272,16 +192,8 @@ function findMessageContentRoot(container: HTMLElement, messageId: string): HTMLreturn 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 {+function highlightAtPoint(ranges: RangeMap, messageId: string, x: number, y: number): string | null {const caret = caretFromPoint(document, x, y);if (!caret) return null;@@ -320,17 +232,3 @@ function caretFromPoint(doc: Document, x: number, y: number): { node: Node; offsfunction nearestElement(node: Node): HTMLElement | null {return node instanceof HTMLElement ? node : node.parentElement;}--function showMenu(e: MouseEvent, items: MenuItem<unknown>[]) {- void contextMenu.show({ x: e.pageX, y: e.pageY, items, selectMenuItemHandler: () => {} });-}--/** Copy the current selection as rich text. The menu opens on mousedown, so the selection is still live. */-function copySelection() {- const ok = document.execCommand("copy");- if (ok) {- toast.showMessage(t("clipboard.copy_success"));- } else {- toast.showError(t("clipboard.copy_failed"));- }-}