Skip to content

Build your personal knowledge base with Trilium Notes

client/AI chat: improve the quoting mechanism

Adorian Doran5e0c3ef1aaf3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fb7697af13..17f2b90d16 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",
+ "quoted_from": "Quoted from",
+ "show_quote_source": "Show quote source",
"copy_message": "Copy message",
"save_to_subnote": "Save to sub-note",
"save_to_subnote_failed": "Failed to create a note from the message.",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
index 47b25e0f70..9862b65ef2 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
@@ -277,8 +277,9 @@
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. */
+/* "Show quote source" jump link at the end of a submitted quote. Inherits link color from
+ `.llm-chat-markdown a`; the pointer cursor is kept explicit since the jump is handled by a click
+ listener rather than real navigation. */
.chat-message-jump {
cursor: pointer;
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
index 5292fb2cd2..4285c13479 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -9,7 +9,7 @@ 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 { renderQuoteSourceLinks } 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";
@@ -112,12 +112,14 @@ 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.
+ // A submitted quote's attribution line is rewritten (before rendering) into a "Show quote source"
+ // jump link back to the quoted message — user messages only, where quotes live.
const renderedContent = useMemo(() => {
if (!isThinking && typeof message.content === "string") {
- const html = renderMarkdown(message.content);
- return message.role === "user" ? linkifyMessageIdReferences(html) : html;
+ const source = message.role === "user"
+ ? renderQuoteSourceLinks(message.content, t("llm_chat.show_quote_source"))
+ : message.content;
+ return renderMarkdown(source);
}
return null;
}, [message.content, isThinking, message.role]);
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 b97798eb44..6dd629668e 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx
@@ -37,7 +37,7 @@ export default function LlmChat({ note, noteContext }: TypeWidgetProps) {
// 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.
+ // Make the "Show quote source" links in submitted quotes jump to the referenced message.
useChatMessageJumps(chat.scrollContainerRef);
const spacedUpdate = useEditorSpacedUpdate({
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.ts
index d12c5a1e3e..9b0f4eef09 100644
--- 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.ts
@@ -108,7 +108,7 @@ export function useChatContextMenu({ chat, noteContext, contextMenuItems }: Chat
items.push({
title: t("llm_chat.quote_selection"),
uiIcon: "bx bxs-quote-alt-left",
- handler: () => appendToInputRef.current(buildQuoteMarkdown(quotedText, messageId))
+ handler: () => appendToInputRef.current(buildQuoteMarkdown(quotedText, messageId, t("llm_chat.quoted_from")))
});
}
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.ts
index 09812bc402..6bbc83a54f 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_markdown.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_markdown.ts
@@ -2,11 +2,15 @@ import { CustomMarkdownRenderer, renderToHtml } from "@triliumnext/commons/src/l
import DOMPurify from "dompurify";
import type { Tokens } from "marked";
+import { MESSAGE_JUMP_CLASS, QUOTE_SOURCE_HREF_PREFIX } from "./chat_quote.js";
+
/**
- * 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.
+ * Renderer that decorates chat-specific markdown links:
+ * - `#root/...` note references get the `reference-link` class so ReadOnlyTextContent's
+ * applyReferenceLinks pass adds the note icon, color, and title (same shape as `[[noteId]]`).
+ * - `#mid-<id>` quote-source links become jump anchors (`chat-message-jump` + `data-message-id`)
+ * that {@link useChatMessageJumps} scrolls to. The id is validated so a hand-crafted link can't
+ * inject attributes.
*/
class ChatMarkdownRenderer extends CustomMarkdownRenderer {
override link(token: Tokens.Link): string {
@@ -14,6 +18,12 @@ class ChatMarkdownRenderer extends CustomMarkdownRenderer {
if (token.href.startsWith("#root/")) {
return html.replace(/^<a\b/, '<a class="reference-link"');
}
+ if (token.href.startsWith(QUOTE_SOURCE_HREF_PREFIX)) {
+ const id = token.href.slice(QUOTE_SOURCE_HREF_PREFIX.length);
+ if (/^[A-Za-z0-9]+$/.test(id)) {
+ return html.replace(/^<a\b/, `<a class="${MESSAGE_JUMP_CLASS}" data-message-id="${id}"`);
+ }
+ }
return html;
}
}
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.ts
index 96f5e882f0..9cde9f51f4 100644
--- 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.ts
@@ -9,7 +9,7 @@ const FLASH_CLASS = "llm-chat-message-jump-target";
const FLASH_DURATION_MS = 1200;
/**
- * Makes the "message ID …" jump links in submitted quotes clickable: scrolls the referenced message
+ * Makes the "Show quote source" 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.
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.ts
index 99d99797f6..2fd73345ca 100644
--- 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.ts
@@ -1,81 +1,106 @@
import { describe, expect, it } from "vitest";
-import { buildQuoteMarkdown, linkifyMessageIdReferences, MESSAGE_JUMP_CLASS } from "./chat_quote.js";
+import { buildQuoteMarkdown, QUOTE_SOURCE_HREF_PREFIX, renderQuoteSourceLinks, stripQuoteSources } from "./chat_quote.js";
describe("buildQuoteMarkdown", () => {
- it("quotes a single line and appends the source", () => {
- expect(buildQuoteMarkdown("The answer is 42.", "msg123")).toBe(
+ it("quotes a single line and appends the attribution with a message-id token", () => {
+ expect(buildQuoteMarkdown("The answer is 42.", "msg123", "Quoted from")).toBe(
"> The answer is 42.\n" +
- "> (Source: message ID msg123)"
+ "> (Quoted from <<mid:msg123>>)"
);
});
it("prefixes every line of a multi-line selection", () => {
- expect(buildQuoteMarkdown("first line\nsecond line", "abc")).toBe(
+ expect(buildQuoteMarkdown("first line\nsecond line", "abc", "Quoted from")).toBe(
"> first line\n" +
"> second line\n" +
- "> (Source: message ID abc)"
+ "> (Quoted from <<mid: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(
+ expect(buildQuoteMarkdown("para one\n\npara two", "abc", "Quoted from")).toBe(
"> para one\n" +
">\n" +
"> para two\n" +
- "> (Source: message ID abc)"
+ "> (Quoted from <<mid:abc>>)"
);
});
- it("drops leading and trailing blank lines but keeps the source line", () => {
- expect(buildQuoteMarkdown("\n \nkept\n \n", "abc")).toBe(
+ it("drops leading and trailing blank lines but keeps the attribution", () => {
+ expect(buildQuoteMarkdown("\n \nkept\n \n", "abc", "Quoted from")).toBe(
"> kept\n" +
- "> (Source: message ID abc)"
+ "> (Quoted from <<mid:abc>>)"
);
});
- it("normalizes CRLF line endings", () => {
- expect(buildQuoteMarkdown("a\r\nb", "abc")).toBe(
- "> a\n" +
+ it("normalizes CRLF and does not alter Markdown characters within the quote", () => {
+ expect(buildQuoteMarkdown("# heading > *stars*\r\nb", "abc", "Quoted from")).toBe(
+ "> # heading > *stars*\n" +
"> b\n" +
- "> (Source: message ID abc)"
+ "> (Quoted from <<mid: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("honours a localized attribution label", () => {
+ expect(buildQuoteMarkdown("x", "abc", "Citat din")).toBe(
+ "> x\n" +
+ "> (Citat din <<mid:abc>>)"
);
});
+});
+
+describe("stripQuoteSources", () => {
+ it("removes the attribution line, keeping the quoted text", () => {
+ const quote = buildQuoteMarkdown("hello", "abc", "Quoted from");
+ expect(stripQuoteSources(`${quote}\n\nmy question`)).toBe("> hello\n\nmy question");
+ });
- it("returns just the source line when the selection is all whitespace", () => {
- expect(buildQuoteMarkdown(" \n\n", "abc")).toBe("> (Source: message ID abc)");
+ it("removes attribution lines regardless of how many tokens are present", () => {
+ const markdown = "> a\n> (Quoted from <<mid:x>>)\n> (Quoted from <<mid:y>>)\n\ntext";
+ expect(stripQuoteSources(markdown)).toBe("> a\n\ntext");
+ });
+
+ it("leaves text with no token untouched", () => {
+ expect(stripQuoteSources("> a normal quote\n\ntext")).toBe("> a normal quote\n\ntext");
});
});
-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>`
+describe("renderQuoteSourceLinks", () => {
+ const label = "Show quote source";
+
+ it("replaces a single-token block's attribution with a jump link", () => {
+ const quote = buildQuoteMarkdown("hello", "abc", "Quoted from");
+ expect(renderQuoteSourceLinks(quote, label)).toBe(
+ "> hello\n" +
+ `> [${label}](${QUOTE_SOURCE_HREF_PREFIX}abc)`
);
});
- 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 a plain user blockquote (no token) untouched", () => {
+ const md = "> just a quote the user typed\n\ntext";
+ expect(renderQuoteSourceLinks(md, label)).toBe(md);
});
- it("leaves text without a source line unchanged", () => {
- expect(linkifyMessageIdReferences("<p>just a normal message</p>")).toBe("<p>just a normal message</p>");
+ it("drops token lines and shows no link when a block has two or more sources", () => {
+ const md = "> a\n> (Quoted from <<mid:x>>)\n> (Quoted from <<mid:y>>)\n\ntext";
+ expect(renderQuoteSourceLinks(md, label)).toBe("> a\n\ntext");
});
- 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"`);
+ it("treats blocks separated by a blank line independently", () => {
+ const md =
+ "> first\n> (Quoted from <<mid:aaa>>)\n\n" +
+ "> second\n> (Quoted from <<mid:bbb>>)";
+ expect(renderQuoteSourceLinks(md, label)).toBe(
+ `> first\n> [${label}](${QUOTE_SOURCE_HREF_PREFIX}aaa)\n\n` +
+ `> second\n> [${label}](${QUOTE_SOURCE_HREF_PREFIX}bbb)`
+ );
+ });
+
+ it("leaves surrounding non-quote text in place", () => {
+ const md = "before\n\n> q\n> (Quoted from <<mid:abc>>)\n\nafter";
+ expect(renderQuoteSourceLinks(md, label)).toBe(
+ `before\n\n> q\n> [${label}](${QUOTE_SOURCE_HREF_PREFIX}abc)\n\nafter`
+ );
});
});
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.ts
index 880a13099c..a3e725bbfc 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_quote.ts
@@ -1,42 +1,82 @@
/**
* 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.
+ * 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
+ * attribution line records which message the excerpt came from via a locale-independent `<<mid:…>>`
+ * token, so `sourceLabel` (e.g. "Quoted from") can be translated freely. Leading and trailing blank
+ * lines are dropped so the quote never carries stray empty rows.
*/
-export function buildQuoteMarkdown(selectedText: string, messageId: string): string {
+export function buildQuoteMarkdown(selectedText: string, messageId: string, sourceLabel: 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)}`);
+ quoted.push(`> (${sourceLabel} <<mid:${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. */
+/** CSS class marking a rendered "Show quote source" link — used for click delegation and styling. */
export const MESSAGE_JUMP_CLASS = "chat-message-jump";
+/** Href scheme for a quote-source link; the referenced message id follows the prefix. */
+export const QUOTE_SOURCE_HREF_PREFIX = "#mid-";
+
+// The message-id anchor embedded in a quote's attribution line. Locale-independent, so the transforms
+// below never depend on the translated "Quoted from" wrapper. Ids are `[A-Za-z0-9]` (from randomString).
+const MID_TOKEN = /<<mid:([A-Za-z0-9]+)>>/;
+const MID_TOKEN_GLOBAL = /<<mid:([A-Za-z0-9]+)>>/g;
+
/**
- * 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.
+ * Remove quote attribution lines (those carrying a `<<mid:…>>` token) from `markdown`, keeping the
+ * quoted text. Used for anything that leaves the chat timeline — the LLM payload and saved notes —
+ * where the message-id anchor is meaningless (and, to the LLM, distracting noise).
*/
-const SOURCE_LINE_PATTERN = /\(Source: message ID ([A-Za-z0-9]+)\)/g;
+export function stripQuoteSources(markdown: string): string {
+ return markdown
+ .split("\n")
+ .filter(line => !MID_TOKEN.test(line))
+ .join("\n");
+}
/**
- * 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.
+ * Rewrite each quote block's attribution line into a "Show quote source" link (Markdown) for display
+ * in the chat timeline. Deliberately forgiving — this is a convenience, never critical:
+ * - a block with exactly one `<<mid:…>>` token gets the link (jumping to that message),
+ * - a block with none is left untouched (an ordinary user blockquote),
+ * - a block with two or more tokens is treated as malformed: its token lines are dropped and no link
+ * is shown, so nothing suspicious (or a raw token) ever surfaces.
+ * `label` is the (localized) link text.
*/
-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>)`);
+export function renderQuoteSourceLinks(markdown: string, label: string): string {
+ const lines = markdown.split("\n");
+ const out: string[] = [];
+ for (let i = 0; i < lines.length;) {
+ if (!isQuoteLine(lines[i])) {
+ out.push(lines[i]);
+ i++;
+ continue;
+ }
+ const start = i;
+ while (i < lines.length && isQuoteLine(lines[i])) i++;
+ out.push(...rewriteQuoteBlock(lines.slice(start, i), label));
+ }
+ return out.join("\n");
+}
+
+/** Whether a line belongs to a Markdown blockquote (starts with `>`). */
+function isQuoteLine(line: string): boolean {
+ return /^\s*>/.test(line);
+}
+
+/** Apply the one/none/many rule to a single contiguous blockquote block. */
+function rewriteQuoteBlock(block: string[], label: string): string[] {
+ const ids = block.flatMap(line => [...line.matchAll(MID_TOKEN_GLOBAL)].map(match => match[1]));
+ if (ids.length === 0) return block;
+ if (ids.length > 1) {
+ return block.filter(line => !MID_TOKEN.test(line)); // ambiguous → drop token lines, no link
+ }
+ const link = `> [${label}](${QUOTE_SOURCE_HREF_PREFIX}${ids[0]})`;
+ return block.map(line => (MID_TOKEN.test(line) ? link : line));
}
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.ts
index b8fb293bb5..5de07d0278 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/chat_save.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_save.ts
@@ -2,6 +2,7 @@ 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";
+import { stripQuoteSources } from "./chat_quote.js";
/**
* Whether the "Save to sub-note" command should be offered for a right-clicked message: only in a
@@ -16,12 +17,13 @@ export function canSaveToSubNote(notePath: string | null | undefined, hasSelecti
/**
* 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.
+ * DOM), so it lands in CKEditor's storage form — math, mermaid diagrams, and code survive intact.
+ * Quote attribution lines are stripped (their message-id anchors are meaningless outside the chat).
+ * 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);
+ const content = renderMarkdown(stripQuoteSources(markdown));
await note_create.createNote(parentNotePath, { content, type: "text", focus: "title" });
} catch (e) {
console.error("Failed to create sub-note from message:", e);
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index d7e3035afc..7cd7e77544 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";
import { randomString } from "../../../services/utils.js";
import { useTriliumEvent } from "../../react/hooks.js";
+import { stripQuoteSources } from "./chat_quote.js";
import { type ContentBlock, type FileBlock, type ImageBlock, type LlmChatContent, type StoredMessage, type TextFileBlock, trimToFirstUserMessage } from "./llm_chat_types.js";
import { useSmoothStreaming } from "./useSmoothStreaming.js";
@@ -64,6 +65,12 @@ function flattenToApiContent(content: string | ContentBlock[]): string | LlmMess
return parts;
}
+/** Strip quote attribution lines from wire content, so the message-id anchors never reach the LLM. */
+function stripQuoteSourcesFromApiContent(content: string | LlmMessagePart[]): string | LlmMessagePart[] {
+ if (typeof content === "string") return stripQuoteSources(content);
+ return content.map(part => (part.type === "text" ? { ...part, text: stripQuoteSources(part.text) } : part));
+}
+
export interface ModelOption extends LlmModelInfo {
costDescription?: string;
}
@@ -499,7 +506,7 @@ export function useLlmChat(
const apiMessages: LlmMessage[] = trimToFirstUserMessage(conversation).map(m => ({
role: m.role,
- content: flattenToApiContent(m.content)
+ content: stripQuoteSourcesFromApiContent(flattenToApiContent(m.content))
}));
const selectedModelProvider = availableModels.find(m => m.id === selectedModel)?.provider;