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
chore(llm): address requested cahnges
Elian Dorande207fac166d
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex a340f19e3a..f6c6b93250 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -14,7 +14,7 @@ import Dropdown from "../../react/Dropdown.js";import { FormDropdownDivider, FormDropdownSubmenu, FormListItem, FormListToggleableItem } from "../../react/FormList.js";import { useLegacyImperativeHandlers } from "../../react/hooks.js";import AddProviderModal, { type LlmProviderConfig } from "../options/llm/AddProviderModal.js";-import { retryImageOnError } from "./retry_image.js";+import { SafeImage } from "./retry_image.js";import { useChatAttachments } from "./useChatAttachments.js";import type { UseLlmChatReturn } from "./useLlmChat.js";@@ -69,11 +69,16 @@ function htmlToPlainText(html: string): string {});// Two-space + newline = markdown hard line break (preserves shift+Enter).container.querySelectorAll("br").forEach((br) => br.replaceWith(" \n"));- const blocks = Array.from(container.children) as HTMLElement[];- if (blocks.length === 0) {- return (container.textContent ?? "").trim();- }- return blocks.map((b) => b.textContent ?? "").join("\n\n").trim();+ // Iterate over all child nodes (not just element children) so top-level+ // text nodes — text not wrapped in a block element — aren't silently dropped.+ const parts: string[] = [];+ container.childNodes.forEach((node) => {+ const text = (node.textContent ?? "").trim();+ if (text) {+ parts.push(text);+ }+ });+ return parts.join("\n\n");}interface ChatInputBarProps {@@ -240,7 +245,7 @@ export default function ChatInputBar({title={att.title}>{att.type === "image" ? (- <img src={att.url} alt={att.title} onError={retryImageOnError} />+ <SafeImage src={att.url} alt={att.title} />) : (<div className="llm-chat-attachment-file"><span className={`bx ${att.type === "file" ? "bxs-file-pdf" : "bxs-file-blank"} llm-chat-attachment-file-icon`} />diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex eef07e7138..bcf69e5c6e 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -12,7 +12,7 @@ import Button from "../../react/Button.js";import { ReadOnlyTextContent } from "../text/ReadOnlyText.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 { retryImageOnError } from "./retry_image.js";+import { SafeImage } from "./retry_image.js";import ToolCallCard from "./ToolCallCard.js";function shortenNumber(n: number): string {@@ -293,7 +293,7 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {className="llm-chat-message-image"title={group.block.title}>- <img src={group.block.url} alt={group.block.title} onError={retryImageOnError} />+ <SafeImage src={group.block.url} alt={group.block.title} /></a>);}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/retry_image.ts b/apps/client/src/widgets/type_widgets/llm_chat/retry_image.tsdeleted file mode 100644index 74974ed0bc..0000000000--- a/apps/client/src/widgets/type_widgets/llm_chat/retry_image.ts+++ /dev/null@@ -1,27 +0,0 @@-/**- * `<img onError={retryImageOnError}>` — retry a failed image load up to three- * times with exponential backoff and a cache-busting query parameter.- *- * Why this exists: when the user uploads an image to a chat note, the server's- * upload endpoint returns the attachment URL *before* the async image-- * processing pipeline has written the actual bytes (see `saveImageToAttachment`- * in `packages/trilium-core/src/services/image.ts`). The first `<img>` fetch- * 404s for a few hundred milliseconds, the browser caches that 404, and the- * preview stays broken even after the image becomes available. Re-requesting- * with a fresh query string sidesteps the cached 404.- */-export function retryImageOnError(e: Event) {- const img = e.currentTarget as HTMLImageElement | null;- if (!img) return;- const tries = Number(img.dataset.retries ?? "0");- if (tries >= 3) return;- // Remember the original URL so successive retries keep cache-busting off- // the same base, not stacking `?_retry=N` parameters.- const base = img.dataset.retryBase ?? img.src.replace(/[?&]_retry=\d+$/, "");- img.dataset.retryBase = base;- img.dataset.retries = String(tries + 1);- const separator = base.includes("?") ? "&" : "?";- setTimeout(() => {- img.src = `${base}${separator}_retry=${tries + 1}`;- }, 300 * (tries + 1));-}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/retry_image.tsx b/apps/client/src/widgets/type_widgets/llm_chat/retry_image.tsxnew file mode 100644index 0000000000..74fc073e2c--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/retry_image.tsx@@ -0,0 +1,46 @@+import { type ImgHTMLAttributes } from "preact/compat";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++/**+ * `<SafeImage>` — retries a failed image load up to three times with exponential+ * backoff and a cache-busting query parameter.+ *+ * Why this exists: when the user uploads an image to a chat note, the server's+ * upload endpoint returns the attachment URL *before* the async image-+ * processing pipeline has written the actual bytes (see `saveImageToAttachment`+ * in `packages/trilium-core/src/services/image.ts`). The first `<img>` fetch+ * 404s for a few hundred milliseconds, the browser caches that 404, and the+ * preview stays broken even after the image becomes available. Re-requesting+ * with a fresh query string sidesteps the cached 404.+ *+ * Why a component (not an onError handler that pokes at `img.src`): chat+ * re-renders frequently during streaming. If the handler mutates the DOM+ * directly, Preact's next diff sees the live `src` (with `?_retry=N`) differs+ * from the VDOM `src` (the original URL) and reverts it, aborting the retry.+ * Owning the URL in component state keeps the VDOM and DOM in agreement.+ */+type SafeImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "onError"> & {+ src: string;+};++export function SafeImage({ src, ...rest }: SafeImageProps) {+ const [currentSrc, setCurrentSrc] = useState(src);+ const retriesRef = useRef(0);++ useEffect(() => {+ retriesRef.current = 0;+ setCurrentSrc(src);+ }, [src]);++ const handleError = useCallback(() => {+ if (retriesRef.current >= 3) return;+ const next = retriesRef.current + 1;+ retriesRef.current = next;+ const separator = src.includes("?") ? "&" : "?";+ setTimeout(() => {+ setCurrentSrc(`${src}${separator}_retry=${next}`);+ }, 300 * next);+ }, [src]);++ return <img {...rest} src={currentSrc} onError={handleError} />;+}diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex 8473e9ac8a..568ec5b3f8 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -61,52 +61,63 @@ function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | FilePaif (part.type === "text") {return { type: "text", text: part.text };}- const attachment = becca.getAttachment(part.attachmentId);- if (!attachment) {- log.error(`LLM message references missing attachment ${part.attachmentId}`);- return null;- }- if (!attachment.isContentAvailable()) {- log.error(`LLM message references protected attachment ${part.attachmentId} without an unlocked session`);- return null;- }- if (part.type === "image") {- const mime = part.mime || attachment.mime;- // SVG isn't accepted by any major provider's vision input, but every- // LLM is fluent in SVG markup — send the XML source as a text part so- // the model can actually read and reason about it.- if (mime === "image/svg+xml") {- const filename = attachment.title || "image.svg";- const text = decodeUtf8(attachment.getContent());+ try {+ const attachment = becca.getAttachment(part.attachmentId);+ if (!attachment) {+ log.error(`LLM message references missing attachment ${part.attachmentId}`);+ return null;+ }+ if (!attachment.isContentAvailable()) {+ log.error(`LLM message references protected attachment ${part.attachmentId} without an unlocked session`);+ return null;+ }+ // Read attachment bytes once — `getContent()` hits the blob store and+ // (for protected attachments) decrypts, so callers shouldn't repeat it.+ const content = attachment.getContent();+ if (part.type === "image") {+ const mime = part.mime || attachment.mime;+ // SVG isn't accepted by any major provider's vision input, but every+ // LLM is fluent in SVG markup — send the XML source as a text part so+ // the model can actually read and reason about it.+ if (mime === "image/svg+xml") {+ const filename = attachment.title || "image.svg";+ const text = decodeUtf8(content);+ return {+ type: "text",+ text: `<file name="${filename}">\n${text}\n</file>`+ };+ }return {- type: "text",- text: `<file name="${filename}">\n${text}\n</file>`+ type: "image",+ image: content,+ mediaType: mime};}+ if (part.type === "file") {+ return {+ type: "file",+ data: content,+ mediaType: part.mime || attachment.mime,+ filename: part.filename || attachment.title+ };+ }+ // type === "text_attachment" — decode the bytes and wrap in a labelled+ // XML-style block. Anthropic recommends this shape and other providers+ // handle it fine; the filename gives the model context about what it's+ // reading without needing provider-specific file APIs.+ const filename = part.filename || attachment.title;+ const text = decodeUtf8(content);return {- type: "image",- image: attachment.getContent(),- mediaType: mime- };- }- if (part.type === "file") {- return {- type: "file",- data: attachment.getContent(),- mediaType: part.mime || attachment.mime,- filename: part.filename || attachment.title+ type: "text",+ text: `<file name="${filename}">\n${text}\n</file>`};+ } catch (err) {+ // A single unreadable attachment (corrupt blob, decryption failure,+ // invalid UTF-8) shouldn't crash the whole chat turn — drop the part+ // and log so the rest of the message still reaches the model.+ log.error(`Failed to resolve message part for attachment ${part.attachmentId}: ${err}`);+ return null;}- // type === "text_attachment" — decode the bytes and wrap in a labelled- // XML-style block. Anthropic recommends this shape and other providers- // handle it fine; the filename gives the model context about what it's- // reading without needing provider-specific file APIs.- const filename = part.filename || attachment.title;- const text = decodeUtf8(attachment.getContent());- return {- type: "text",- text: `<file name="${filename}">\n${text}\n</file>`- };}/**