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: implement a "quote selection" feature
Adorian Dorane116b3a337d2
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 589d9dfae1..e232025771 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2077,6 +2077,7 @@"highlight_add": "Highlight","highlight_remove": "Remove highlight","highlight_remove_confirm": "Remove this highlight?",+ "quote_selection": "Quote selection","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/react/CKEditor.tsx b/apps/client/src/widgets/react/CKEditor.tsxindex 84df2d0599..391fd41a52 100644--- a/apps/client/src/widgets/react/CKEditor.tsx+++ b/apps/client/src/widgets/react/CKEditor.tsx@@ -12,6 +12,15 @@ export interface CKEditorApi {* @param text text to set in the editor*/setText(text: string): void;+ /**+ * Appends `text` to the end of the editor as its own block, translating embedded newlines into+ * soft breaks, then leaves two blank lines below it for visual separation with the cursor on the+ * last one, and focuses the editor. Existing content is preserved; an empty editor gets the text+ * at the top with no leading blank.+ *+ * @param text text to append (may contain `\n`)+ */+ appendBlock(text: string): void;}interface CKEditorOpts {@@ -46,6 +55,40 @@ export default function CKEditor({ apiRef, currentValue, editor, config, disable},setText(text: string) {textEditorRef.current?.setData(text);+ },+ appendBlock(text: string) {+ const editor = textEditorRef.current;+ if (!editor) return;+ editor.model.change((writer) => {+ const root = editor.model.document.getRoot();+ if (!root) return;++ // An untouched editor holds a single empty paragraph — drop it so the quote+ // starts at the top with no leading blank line.+ const onlyChild = root.childCount === 1 ? root.getChild(0) : null;+ if (onlyChild?.is("element", "paragraph") && onlyChild.isEmpty) {+ writer.remove(onlyChild);+ }++ // The text block: one paragraph, its lines joined by soft breaks so the whole+ // excerpt stays a single block (a bare `writer.insert` keeps it from merging into+ // the preceding paragraph, giving the blank-line separation we want).+ const paragraph = writer.createElement("paragraph");+ text.split("\n").forEach((line, index) => {+ if (index > 0) writer.appendElement("softBreak", paragraph);+ if (line.length > 0) writer.appendText(line, paragraph);+ });+ writer.insert(paragraph, writer.createPositionAt(root, "end"));++ // Two trailing empty paragraphs separate the appended block from where the user+ // types; the cursor lands on the last one.+ const blankLine = writer.createElement("paragraph");+ writer.insert(blankLine, writer.createPositionAfter(paragraph));+ const cursorParagraph = writer.createElement("paragraph");+ writer.insert(cursorParagraph, writer.createPositionAfter(blankLine));+ writer.setSelection(cursorParagraph, "in");+ });+ editor.editing.view.focus();}};}, [ editorContainerRef ]);diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex f6c6b93250..01e8c6f1e8 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -143,6 +143,15 @@ export default function ChatInputBar({}, [baseSubmit, chat.input, chat.isStreaming, chat.pendingAttachments.length]);submitRef.current = handleSubmit;+ // Expose the reply-input editor to the chat hook so timeline actions (e.g. quoting a selection)+ // can write into it. A stable wrapper reads the live api ref, so it works regardless of whether+ // the CKEditor's imperative handle has committed by the time this effect first runs.+ const registerInputEditor = chat.registerInputEditor;+ useEffect(() => {+ registerInputEditor({ appendBlock: (text) => editorApiRef.current?.appendBlock(text) });+ return () => registerInputEditor(undefined);+ }, [registerInputEditor]);+// Reflect streaming state into CKEditor's read-only lock.useEffect(() => {const editor = editorInstanceRef.current;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.cssindex e00e5ce3bd..47b25e0f70 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css@@ -277,6 +277,24 @@font-style: italic;}+/* "message ID …" jump link in a submitted quote's source line. Inherits link color from+ `.llm-chat-markdown a`; only the pointer cursor is needed since it carries no href. */+.chat-message-jump {+ cursor: pointer;+}++/* Flash the referenced bubble when jumped to. A box-shadow outline pulse (no layout shift)+ works on both the user bubble and the transparent assistant bubble. Duration mirrors+ FLASH_DURATION_MS in chat_message_jump.ts. */+.llm-chat-message-wrapper.llm-chat-message-jump-target .llm-chat-message {+ animation: llm-chat-jump-flash 1.2s ease-out;+}++@keyframes llm-chat-jump-flash {+ from { box-shadow: 0 0 0 2px var(--quick-search-result-highlight-color, #007bff); }+ to { box-shadow: 0 0 0 2px transparent; }+}+/* Message footer (timestamp + token usage, sits below the bubble) */.llm-chat-footer {position: absolute;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex b7151dd897..af4000fdac 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -11,6 +11,7 @@ import { t } from "../../../services/i18n.js";import utils from "../../../services/utils.js";import Button from "../../react/Button.js";import { ReadOnlyTextContent } from "../text/ReadOnlyText.js";+import { linkifyMessageIdReferences } from "./chat_quote.js";import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";import { type ContentBlock, type FileBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type TextFileBlock, type ToolCallBlock } from "./llm_chat_types.js";import { SafeImage } from "./retry_image.js";@@ -139,12 +140,15 @@ export default function ChatMessage({ message, isStreaming, onRetry }: Props) {// Render markdown for plain-string content (assistant legacy content and user prompts).// User prompts may contain `[Title](#root/noteId)` reference links produced by the// chat input's @-mention feature, which markdown renders as proper clickable links.+ // A submitted quote's "message ID …" source line is turned into a jump link back to the+ // quoted message — user messages only, where those source lines live.const renderedContent = useMemo(() => {if (!isThinking && typeof message.content === "string") {- return renderMarkdown(message.content);+ const html = renderMarkdown(message.content);+ return message.role === "user" ? linkifyMessageIdReferences(html) : html;}return null;- }, [message.content, isThinking]);+ }, [message.content, isThinking, message.role]);const messageClasses = ["llm-chat-message",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsxindex 765999ca0e..db0a5b48a9 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx@@ -6,6 +6,7 @@ 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 { useChatMessageJumps } from "./chat_message_jump.js";import { useChatToc } from "./chat_toc.js";import ChatInputBar from "./ChatInputBar.js";import ChatMessageList from "./ChatMessageList.js";@@ -32,6 +33,9 @@ export default function LlmChat({ note, noteContext }: TypeWidgetProps) {// Paint user-created highlights over the replies and publish them for the sidebar widget.useChatHighlights(chat, noteContext);+ // Make the "message ID …" links in submitted quotes jump to the referenced message.+ useChatMessageJumps(chat.scrollContainerRef);+const spacedUpdate = useEditorSpacedUpdate({note,noteType: "llmChat",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 04ce9f6377..9c7783d396 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@@ -8,6 +8,7 @@ import { t } from "../../../services/i18n.js";import toast from "../../../services/toast.js";import { randomString } from "../../../services/utils.js";import { createAnchorFromSelection, resolveAnchorRange } from "./chat_highlights_anchor.js";+import { buildQuoteMarkdown } from "./chat_quote.js";import type { HighlightAnchor } from "./llm_chat_types.js";import type { UseLlmChatReturn } from "./useLlmChat.js";@@ -59,6 +60,8 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConteisStreamingRef.current = isStreaming;const setMessagesRef = useRef(chat.setMessages);setMessagesRef.current = chat.setMessages;+ const appendToInputRef = useRef(chat.appendToInput);+ appendToInputRef.current = chat.appendToInput;// 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@@ -155,6 +158,18 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConteitems.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))+ });+ }+if (items.length === 0) return; // nothing to do → leave the native menue.preventDefault();showMenu(e, items);diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_message_jump.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_message_jump.tsnew file mode 100644index 0000000000..96f5e882f0--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_message_jump.ts@@ -0,0 +1,47 @@+import type { RefObject } from "preact";+import { useEffect } from "preact/hooks";++import { MESSAGE_JUMP_CLASS } from "./chat_quote.js";++/** Transient class that flashes the jumped-to message so the user sees where they landed. */+const FLASH_CLASS = "llm-chat-message-jump-target";+/** Kept in sync with the flash animation duration in ChatMessage.css. */+const FLASH_DURATION_MS = 1200;++/**+ * Makes the "message ID …" jump links in submitted quotes clickable: scrolls the referenced message+ * into view and briefly flashes it. One delegated listener on the timeline covers the links in every+ * message, so there's no per-message wiring. A missing target (the referenced message was deleted or+ * regenerated) is a graceful no-op — mirroring how highlights drop orphaned anchors.+ */+export function useChatMessageJumps(scrollContainerRef: RefObject<HTMLElement>) {+ useEffect(() => {+ const container = scrollContainerRef.current;+ if (!container) return;++ const onClick = (e: MouseEvent) => {+ const link = (e.target as HTMLElement | null)?.closest<HTMLElement>(`.${MESSAGE_JUMP_CLASS}`);+ const targetId = link?.dataset.messageId;+ if (!targetId) return;+ e.preventDefault();++ // 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.+ let wrapper: HTMLElement | null = null;+ for (const el of container.querySelectorAll<HTMLElement>("[data-message-id]")) {+ if (el.dataset.messageId === targetId) { wrapper = el; break; }+ }+ if (!wrapper) return; // referenced message is gone — nothing to jump to++ wrapper.scrollIntoView({ block: "center", behavior: "smooth" });+ // Re-trigger the flash on repeat clicks: remove, force a reflow, then re-add.+ wrapper.classList.remove(FLASH_CLASS);+ void wrapper.offsetWidth;+ wrapper.classList.add(FLASH_CLASS);+ window.setTimeout(() => wrapper.classList.remove(FLASH_CLASS), FLASH_DURATION_MS);+ };++ container.addEventListener("click", onClick);+ return () => container.removeEventListener("click", onClick);+ }, [scrollContainerRef]);+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.spec.tsnew file mode 100644index 0000000000..99d99797f6--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.spec.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";++import { buildQuoteMarkdown, linkifyMessageIdReferences, MESSAGE_JUMP_CLASS } from "./chat_quote.js";++describe("buildQuoteMarkdown", () => {+ it("quotes a single line and appends the source", () => {+ expect(buildQuoteMarkdown("The answer is 42.", "msg123")).toBe(+ "> The answer is 42.\n" ++ "> (Source: message ID msg123)"+ );+ });++ it("prefixes every line of a multi-line selection", () => {+ expect(buildQuoteMarkdown("first line\nsecond line", "abc")).toBe(+ "> first line\n" ++ "> second line\n" ++ "> (Source: message ID abc)"+ );+ });++ it("keeps blank lines inside the selection as a bare '>' so the quote stays contiguous", () => {+ expect(buildQuoteMarkdown("para one\n\npara two", "abc")).toBe(+ "> para one\n" ++ ">\n" ++ "> para two\n" ++ "> (Source: message ID abc)"+ );+ });++ it("drops leading and trailing blank lines but keeps the source line", () => {+ expect(buildQuoteMarkdown("\n \nkept\n \n", "abc")).toBe(+ "> kept\n" ++ "> (Source: message ID abc)"+ );+ });++ it("normalizes CRLF line endings", () => {+ expect(buildQuoteMarkdown("a\r\nb", "abc")).toBe(+ "> a\n" ++ "> b\n" ++ "> (Source: message ID abc)"+ );+ });++ it("does not escape or alter Markdown characters within the quoted text", () => {+ expect(buildQuoteMarkdown("# heading with > and *stars*", "abc")).toBe(+ "> # heading with > and *stars*\n" ++ "> (Source: message ID abc)"+ );+ });++ it("returns just the source line when the selection is all whitespace", () => {+ expect(buildQuoteMarkdown(" \n\n", "abc")).toBe("> (Source: message ID abc)");+ });+});++describe("linkifyMessageIdReferences", () => {+ it("wraps the message id in a jump link, leaving surrounding text intact", () => {+ expect(linkifyMessageIdReferences("<p>(Source: message ID abc123)</p>")).toBe(+ `<p>(Source: <a class="${MESSAGE_JUMP_CLASS}" data-message-id="abc123">message ID abc123</a>)</p>`+ );+ });++ it("linkifies the source line produced by buildQuoteMarkdown", () => {+ const source = buildQuoteMarkdown("hello", "Xy9Z");+ // Simulate the rendered prose (the phrase survives markdown rendering verbatim).+ expect(linkifyMessageIdReferences(source)).toContain(+ `<a class="${MESSAGE_JUMP_CLASS}" data-message-id="Xy9Z">message ID Xy9Z</a>`+ );+ });++ it("leaves text without a source line unchanged", () => {+ expect(linkifyMessageIdReferences("<p>just a normal message</p>")).toBe("<p>just a normal message</p>");+ });++ it("links every occurrence when a message quotes more than once", () => {+ const html = linkifyMessageIdReferences("(Source: message ID aaa) ... (Source: message ID bbb)");+ expect(html).toContain(`data-message-id="aaa"`);+ expect(html).toContain(`data-message-id="bbb"`);+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.tsnew file mode 100644index 0000000000..880a13099c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.ts@@ -0,0 +1,42 @@+/**+ * Format a selected stretch of a chat message as a Markdown blockquote for the reply input.+ *+ * Every line is prefixed with `> ` so the whole excerpt renders as one contiguous blockquote —+ * blank lines inside the selection become a bare `>` so the quote isn't split into two. A trailing+ * source line records which message the excerpt came from, which is useful context for the LLM.+ * Leading and trailing blank lines are dropped so the quote never carries stray empty rows.+ */+export function buildQuoteMarkdown(selectedText: string, messageId: string): string {+ const lines = selectedText.replace(/\r\n/g, "\n").split("\n");+ while (lines.length && !lines[0].trim()) lines.shift();+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();++ const quoted = lines.map(line => (line.trim() ? `> ${line}` : ">"));+ quoted.push(`> ${sourceLine(messageId)}`);+ return quoted.join("\n");+}++/** The trailing line of a quote block, recording which message the excerpt came from. */+function sourceLine(messageId: string): string {+ return `(Source: message ID ${messageId})`;+}++/** CSS class marking a rendered "message ID …" jump link — used for click delegation and styling. */+export const MESSAGE_JUMP_CLASS = "chat-message-jump";++/**+ * Matches the source line emitted by {@link sourceLine} in already-rendered message HTML. Kept next+ * to the builder so the two can't drift. The capture is the referenced message id — `[A-Za-z0-9]`+ * (from `randomString`), so it's safe to drop straight into an attribute without escaping.+ */+const SOURCE_LINE_PATTERN = /\(Source: message ID ([A-Za-z0-9]+)\)/g;++/**+ * Turn the "message ID …" text of a quote's source line into a link back to that message. A+ * render-time enhancement only — the stored and submitted text stays plain markdown, so the composer+ * and the LLM never see link markup. Apply to user-message HTML, where quote source lines live.+ */+export function linkifyMessageIdReferences(html: string): string {+ return html.replace(SOURCE_LINE_PATTERN, (_match, id) =>+ `(Source: <a class="${MESSAGE_JUMP_CLASS}" data-message-id="${id}">message ID ${id}</a>)`);+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex 63f730e18f..41a3332243 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -11,6 +11,11 @@ import { useSmoothStreaming } from "./useSmoothStreaming.js";/** A user-supplied attachment waiting to be sent with the next message. */export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;+/** The subset of the reply-input editor API the chat needs to write into it imperatively. */+export interface InputEditorApi {+ appendBlock(text: string): void;+}+/** Distance (px) past the content bottom edge within which the timeline counts as "at bottom". */const SCROLL_BOTTOM_THRESHOLD = 50;/**@@ -107,6 +112,11 @@ export interface UseLlmChatReturn {/** Whether we're still checking for providers */isCheckingProvider: boolean;+ /** Register the reply-input editor so message-timeline actions (e.g. quoting) can write into it. */+ registerInputEditor: (api: InputEditorApi | undefined) => void;+ /** Append a preformatted block (e.g. a Markdown quote) to the reply input and focus it. */+ appendToInput: (text: string) => void;+// SetterssetInput: (value: string) => void;setMessages: (messages: StoredMessage[]) => void;@@ -200,6 +210,16 @@ export function useLlmChat(const pendingAttachmentsRef = useRef(pendingAttachments);pendingAttachmentsRef.current = pendingAttachments;+ // The reply-input editor, registered by ChatInputBar once mounted. Held in a ref so timeline+ // actions (e.g. quoting a selection) can write into it without a render-order dependency.+ const inputEditorRef = useRef<InputEditorApi | undefined>();+ const registerInputEditor = useCallback((api: InputEditorApi | undefined) => {+ inputEditorRef.current = api;+ }, []);+ const appendToInput = useCallback((text: string) => {+ inputEditorRef.current?.appendBlock(text);+ }, []);+const addPendingAttachment = useCallback((attachment: AttachmentBlock) => {setPendingAttachments(prev => [...prev, attachment]);}, []);@@ -815,6 +835,9 @@ export function useLlmChat(hasProvider,isCheckingProvider,+ registerInputEditor,+ appendToInput,+// SetterssetInput,setMessages,