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 saving a message as a sub-note (no formatting loss)
Adorian Doran32d969c73143
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e232025771..618ec8615e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2078,6 +2078,8 @@"highlight_remove": "Remove highlight","highlight_remove_confirm": "Remove this highlight?","quote_selection": "Quote selection",+ "save_to_subnote": "Save to sub-note",+ "save_to_subnote_failed": "Failed to create a note from the message.","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/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex af4000fdac..5292fb2cd2 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -2,15 +2,13 @@ import "./ChatMessage.css";import "../markdown/MarkdownCommons.css";import { type LlmCitation } from "@triliumnext/commons";-import { CustomMarkdownRenderer, renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer";-import DOMPurify from "dompurify";-import type { Tokens } from "marked";import { useMemo } from "preact/hooks";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 { renderMarkdown } from "./chat_markdown.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";@@ -23,32 +21,6 @@ function shortenNumber(n: number): string {return n.toString();}-/**- * Renderer that tags `#root/...` markdown links with the `reference-link` class- * so ReadOnlyTextContent's applyReferenceLinks pass decorates them with the- * note icon, color, and title — same shape as the `[[noteId]]` wiki-link- * extension's output, but for chat's `[Title](#root/noteId)` references.- */-class ChatMarkdownRenderer extends CustomMarkdownRenderer {- override link(token: Tokens.Link): string {- const html = super.link(token);- if (token.href.startsWith("#root/")) {- return html.replace(/^<a\b/, '<a class="reference-link"');- }- return html;- }-}--/** Parse markdown to HTML using the shared rendering pipeline. */-function renderMarkdown(markdown: string): string {- return renderToHtml(markdown, "", {- sanitize: (h) => DOMPurify.sanitize(h),- wikiLink: { formatHref: (id) => `#root/${id}` },- demoteH1: false,- renderer: new ChatMarkdownRenderer({ async: false })- });-}-/** Renders markdown content using the shared read-only text pipeline (math, syntax highlighting, mermaid, etc.). */function MarkdownContent({ html, isStreaming }: { html: string; isStreaming?: boolean }) {return (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 9c7783d396..ff7a8d317d 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@@ -9,7 +9,8 @@ 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 { canSaveToSubNote, saveMessageToSubNote } from "./chat_save.js";+import { getMessageText, type HighlightAnchor } from "./llm_chat_types.js";import type { UseLlmChatReturn } from "./useLlmChat.js";/** A highlight surfaced in the sidebar list. */@@ -62,6 +63,10 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteContesetMessagesRef.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,11 +131,11 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConteelement?.scrollIntoView({ block: "center", behavior: "smooth" });}, []);- // Right-click menu over the timeline: Copy the selection (or highlighted text), plus Remove when- // the click lands on a highlight or Highlight for a prose selection. 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, so ordinary right-clicks are untouched. Copy stays available while a- // reply streams; only the message-mutating add/remove are suppressed then.+ // Right-click menu over the timeline. With a text selection: Copy, Quote, and Add/Remove+ // highlight. With no selection: Save the whole message to a sub-note (note chats only). 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; only the+ // message-mutating add/remove are suppressed then.useEffect(() => {const container = scrollContainerRef.current;if (!container) return;@@ -170,6 +175,23 @@ export function useChatHighlights(chat: UseLlmChatReturn, noteContext: NoteConte});}+ // 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 savedMessage = messagesRef.current.find(m => m.id === messageId);+ const savedMarkdown = savedMessage ? getMessageText(savedMessage.content) : "";+ if (parentNotePath && canSaveToSubNote(parentNotePath, hasSelection, savedMarkdown)) {+ items.push({+ title: t("llm_chat.save_to_subnote"),+ uiIcon: "bx bx-save",+ handler: () => void saveMessageToSubNote(parentNotePath, savedMarkdown)+ });+ }+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_markdown.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_markdown.tsnew file mode 100644index 0000000000..09812bc402--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_markdown.ts@@ -0,0 +1,33 @@+import { CustomMarkdownRenderer, renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer";+import DOMPurify from "dompurify";+import type { Tokens } from "marked";++/**+ * Renderer that tags `#root/...` markdown links with the `reference-link` class+ * so ReadOnlyTextContent's applyReferenceLinks pass decorates them with the+ * note icon, color, and title — same shape as the `[[noteId]]` wiki-link+ * extension's output, but for chat's `[Title](#root/noteId)` references.+ */+class ChatMarkdownRenderer extends CustomMarkdownRenderer {+ override link(token: Tokens.Link): string {+ const html = super.link(token);+ if (token.href.startsWith("#root/")) {+ return html.replace(/^<a\b/, '<a class="reference-link"');+ }+ return html;+ }+}++/**+ * Parse chat markdown to HTML using the shared rendering pipeline. The output is CKEditor's storage+ * form (math as `math-tex` spans, mermaid as `language-mermaid` code blocks, plain code blocks,+ * `reference-link` anchors), so it renders identically in the chat timeline and in a saved text note.+ */+export function renderMarkdown(markdown: string): string {+ return renderToHtml(markdown, "", {+ sanitize: (h) => DOMPurify.sanitize(h),+ wikiLink: { formatHref: (id) => `#root/${id}` },+ demoteH1: false,+ renderer: new ChatMarkdownRenderer({ async: false })+ });+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_save.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_save.spec.tsnew file mode 100644index 0000000000..30fdf28e5d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_save.spec.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import { canSaveToSubNote } from "./chat_save.js";++describe("canSaveToSubNote", () => {+ it("offers the command in a note chat with no selection and a non-empty message", () => {+ expect(canSaveToSubNote("root/abc", false, "some reply text")).toBe(true);+ });++ it("hides the command when text is selected (the selection commands apply instead)", () => {+ expect(canSaveToSubNote("root/abc", true, "some reply text")).toBe(false);+ });++ it("hides the command outside a note chat (no parent note path)", () => {+ expect(canSaveToSubNote(undefined, false, "some reply text")).toBe(false);+ expect(canSaveToSubNote(null, false, "some reply text")).toBe(false);+ });++ it("hides the command when the message has no text to save", () => {+ expect(canSaveToSubNote("root/abc", false, "")).toBe(false);+ expect(canSaveToSubNote("root/abc", false, " \n\t ")).toBe(false);+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_save.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_save.tsnew file mode 100644index 0000000000..b8fb293bb5--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_save.ts@@ -0,0 +1,30 @@+import { t } from "../../../services/i18n.js";+import note_create from "../../../services/note_create.js";+import toast from "../../../services/toast.js";+import { renderMarkdown } from "./chat_markdown.js";++/**+ * Whether the "Save to sub-note" command should be offered for a right-clicked message: only in a+ * note chat (a note to parent under), only with no active text selection (a selection means the+ * selection commands apply, and a whole-message save would be confusing), and only when the message+ * actually has text to save.+ */+export function canSaveToSubNote(notePath: string | null | undefined, hasSelection: boolean, markdown: string): boolean {+ return !!notePath && !hasSelection && markdown.trim().length > 0;+}++/**+ * Create a text child note from a message's markdown under `parentNotePath` and open it in the active+ * tab. The content is rendered from the message's markdown source (not scraped from the rendered chat+ * DOM), so it lands in CKEditor's storage form — math, mermaid diagrams, and code survive intact. The+ * note is created untitled with the title field focused, so the user names it themselves.+ */+export async function saveMessageToSubNote(parentNotePath: string, markdown: string) {+ try {+ const content = renderMarkdown(markdown);+ await note_create.createNote(parentNotePath, { content, type: "text", focus: "title" });+ } catch (e) {+ console.error("Failed to create sub-note from message:", e);+ toast.showError(t("llm_chat.save_to_subnote_failed"));+ }+}