Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): basic support for images

Elian Doran2544b300ab1e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 94408a0a04..39186b2a9b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1813,7 +1813,11 @@
"no_provider_message": "No AI provider configured. Add one to start chatting.",
"add_provider": "Add AI Provider",
"stop": "Stop",
- "retry": "Retry"
+ "retry": "Retry",
+ "attach_image": "Attach image",
+ "remove_attachment": "Remove attachment",
+ "image_upload_failed": "Failed to upload image \"{{name}}\".",
+ "image_unsupported_type": "\"{{name}}\" isn't a supported image type. Use PNG, JPEG, GIF, or WebP."
},
"sidebar_chat": {
"title": "AI Chat",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
index 0a68f04142..b0bddebd26 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
@@ -7,6 +7,62 @@
border-top: 1px solid var(--main-border-color);
}
+/* Attachment preview row above the editor */
+.llm-chat-attachments {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.llm-chat-attachment-chip {
+ position: relative;
+ width: 56px;
+ height: 56px;
+ border-radius: 6px;
+ overflow: hidden;
+ border: 1px solid var(--main-border-color);
+ background: var(--accented-background-color);
+}
+
+.llm-chat-attachment-chip img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.llm-chat-attachment-remove {
+ position: absolute;
+ top: 2px;
+ right: 2px;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: none;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, 0.6);
+ color: white;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 0.9rem;
+ line-height: 1;
+}
+
+.llm-chat-attachment-remove:hover:not(:disabled) {
+ background: rgba(0, 0, 0, 0.85);
+}
+
+.llm-chat-attachment-remove:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.llm-chat-attach-btn {
+ font-size: 1.1rem;
+}
+
.llm-chat-input {
flex: 1;
min-height: 60px;
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index ec7fbbc8a2..12a94869ae 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -7,6 +7,8 @@ import { t } from "../../../services/i18n.js";
import link from "../../../services/link.js";
import note_autocomplete, { type Suggestion } from "../../../services/note_autocomplete.js";
import options from "../../../services/options.js";
+import server from "../../../services/server.js";
+import toast from "../../../services/toast.js";
import ActionButton from "../../react/ActionButton.js";
import Button from "../../react/Button.js";
import CKEditor, { type CKEditorApi } from "../../react/CKEditor.js";
@@ -14,8 +16,12 @@ 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 type { ImageBlock } from "./llm_chat_types.js";
import type { UseLlmChatReturn } from "./useLlmChat.js";
+/** MIME types we accept for image upload — must match what the providers support as vision input. */
+const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"];
+
const READ_ONLY_LOCK = "llm-chat-streaming";
const mentionFeeds: MentionFeed[] = [
@@ -49,6 +55,43 @@ function formatTokenCount(tokens: number): string {
return tokens.toLocaleString();
}
+/**
+ * Upload an image file as an attachment to the chat note and return a block
+ * describing it. The server's `notes/{id}/attachments/upload` endpoint already
+ * handles image-role classification and returns a stable URL we can render
+ * inline; we just feed it back as an `ImageBlock`.
+ */
+async function uploadImageAsAttachment(noteId: string, file: File): Promise<ImageBlock | null> {
+ let detail: string | undefined;
+ try {
+ const result = await server.upload(
+ `notes/${noteId}/attachments/upload`,
+ file, undefined, "POST"
+ ) as { uploaded?: boolean; url?: string; message?: string };
+ if (result?.uploaded && result.url) {
+ // The upload endpoint returns the URL as `api/attachments/<id>/image/<title>`.
+ // Pull the attachment ID back out so we can pass it to the server.
+ const match = result.url.match(/attachments\/([^/]+)\/image\//);
+ if (match) {
+ return {
+ type: "image",
+ attachmentId: match[1],
+ mime: file.type,
+ title: file.name,
+ url: result.url
+ };
+ }
+ }
+ detail = result?.message;
+ } catch (e) {
+ detail = e instanceof Error ? e.message : undefined;
+ }
+
+ const base = t("llm_chat.image_upload_failed", { name: file.name });
+ toast.showError(detail ? `${base} ${detail}` : base);
+ return null;
+}
+
/**
* Convert CKEditor HTML into plain text suitable for an LLM prompt.
*
@@ -106,9 +149,71 @@ export default function ChatInputBar({
const [showAddProviderModal, setShowAddProviderModal] = useState(false);
const editorApiRef = useRef<CKEditorApi>();
const editorInstanceRef = useRef<CKTextEditor>();
+ const fileInputRef = useRef<HTMLInputElement>(null);
// Always-fresh submit handler for the editor's enter listener.
const submitRef = useRef<(e: Event) => void>(() => {});
+ /** Upload an image file to the chat note and add the result to pending attachments. */
+ const uploadFile = useCallback(async (file: File) => {
+ if (!chat.chatNoteId) return;
+ if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) {
+ toast.showError(t("llm_chat.image_unsupported_type", { name: file.name }));
+ return;
+ }
+ const block = await uploadImageAsAttachment(chat.chatNoteId, file);
+ if (block) {
+ chat.addPendingAttachment(block);
+ }
+ }, [chat]);
+
+ const handleFilePickerChange = useCallback(async (e: Event) => {
+ const target = e.target as HTMLInputElement;
+ const files = target.files;
+ if (!files) return;
+ for (const file of Array.from(files)) {
+ await uploadFile(file);
+ }
+ // Reset so the same file can be picked again later.
+ target.value = "";
+ }, [uploadFile]);
+
+ const handlePaste = useCallback(async (e: ClipboardEvent) => {
+ const items = e.clipboardData?.items;
+ if (!items) return;
+ const imageFiles: File[] = [];
+ for (const item of Array.from(items)) {
+ if (item.kind === "file" && item.type.startsWith("image/")) {
+ const file = item.getAsFile();
+ if (file) imageFiles.push(file);
+ }
+ }
+ if (imageFiles.length === 0) return;
+ // Stop CKEditor from also pasting the image as an inline data URL — we
+ // want it as an attachment, not embedded markup.
+ e.preventDefault();
+ e.stopPropagation();
+ for (const file of imageFiles) {
+ await uploadFile(file);
+ }
+ }, [uploadFile]);
+
+ const handleDrop = useCallback(async (e: DragEvent) => {
+ const files = e.dataTransfer?.files;
+ if (!files || files.length === 0) return;
+ e.preventDefault();
+ e.stopPropagation();
+ for (const file of Array.from(files)) {
+ await uploadFile(file);
+ }
+ }, [uploadFile]);
+
+ const handleDragOver = useCallback((e: DragEvent) => {
+ // Required for the drop event to fire.
+ if (e.dataTransfer?.types.includes("Files")) {
+ e.preventDefault();
+ }
+ }, []);
+
// CKEditor's ReferenceLink plugin calls back into the parent component to
// resolve a note's title from its href.
useLegacyImperativeHandlers({
@@ -124,13 +229,13 @@ export default function ChatInputBar({
// chat.input) avoids the React-render / CKEditor-change-event race that left the
// editor visually populated after submit.
const handleSubmit = useCallback((e: Event) => {
- const willSubmit = chat.input.trim() && !chat.isStreaming;
+ const willSubmit = (chat.input.trim() || chat.pendingAttachments.length > 0) && !chat.isStreaming;
baseSubmit(e);
if (willSubmit) {
editorApiRef.current?.setText("");
editorApiRef.current?.focus();
}
- }, [baseSubmit, chat.input, chat.isStreaming]);
+ }, [baseSubmit, chat.input, chat.isStreaming, chat.pendingAttachments.length]);
submitRef.current = handleSubmit;
// Reflect streaming state into CKEditor's read-only lock.
@@ -215,7 +320,30 @@ export default function ChatInputBar({
}
return (
- <form className="llm-chat-input-form" onSubmit={handleSubmit}>
+ <form
+ className="llm-chat-input-form"
+ onSubmit={handleSubmit}
+ onDrop={handleDrop}
+ onDragOver={handleDragOver}
+ >
+ {chat.pendingAttachments.length > 0 && (
+ <div className="llm-chat-attachments">
+ {chat.pendingAttachments.map((att) => (
+ <div key={att.attachmentId} className="llm-chat-attachment-chip">
+ <img src={att.url} alt={att.title} />
+ <button
+ type="button"
+ className="llm-chat-attachment-remove"
+ title={t("llm_chat.remove_attachment")}
+ onClick={() => chat.removePendingAttachment(att.attachmentId)}
+ disabled={chat.isStreaming}
+ >
+ <span className="bx bx-x" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
<CKEditor
apiRef={editorApiRef}
className="llm-chat-input"
@@ -243,8 +371,20 @@ export default function ChatInputBar({
},
{ priority: "high" }
);
+ // Capture pasted images at the DOM layer so CKEditor doesn't
+ // try to embed them as base64 data URLs inside the editor.
+ const editable = editor.editing.view.getDomRoot();
+ editable?.addEventListener("paste", handlePaste as unknown as EventListener, { capture: true });
}}
/>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept={ACCEPTED_IMAGE_TYPES.join(",")}
+ multiple
+ onChange={handleFilePickerChange}
+ style={{ display: "none" }}
+ />
<div className="llm-chat-options">
<div className="llm-chat-model-selector">
<span className="bx bx-chip" />
@@ -333,11 +473,18 @@ export default function ChatInputBar({
</div>
)}
</div>
+ <ActionButton
+ icon="bx bx-image-add"
+ text={t("llm_chat.attach_image")}
+ onClick={() => fileInputRef.current?.click()}
+ disabled={chat.isStreaming || !chat.chatNoteId}
+ className="llm-chat-attach-btn"
+ />
<ActionButton
icon={chat.isStreaming ? "bx bx-stop" : "bx bx-send"}
text={chat.isStreaming ? t("llm_chat.stop") : t("llm_chat.send")}
onClick={chat.isStreaming ? chat.stopStreaming : handleSubmit}
- disabled={!chat.isStreaming && !chat.input.trim()}
+ disabled={!chat.isStreaming && !chat.input.trim() && chat.pendingAttachments.length === 0}
className={`llm-chat-send-btn ${chat.isStreaming ? "llm-chat-stop-btn" : ""}`}
/>
</div>
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 ee447508d2..969182cd19 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css
@@ -39,6 +39,19 @@
line-height: 1.5;
}
+.llm-chat-message-image {
+ display: block;
+ margin: 0.5rem 0;
+ max-width: 100%;
+}
+
+.llm-chat-message-image img {
+ max-width: 100%;
+ max-height: 280px;
+ border-radius: 6px;
+ border: 1px solid var(--main-border-color);
+}
+
.llm-chat-cursor {
display: inline-block;
width: 8px;
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 e2aa707201..138641f524 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx
@@ -11,7 +11,7 @@ import utils from "../../../services/utils.js";
import Button from "../../react/Button.js";
import { ReadOnlyTextContent } from "../text/ReadOnlyText.js";
import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";
-import { type ContentBlock, getMessageText, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";
+import { type ContentBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";
import ToolCallCard from "./ToolCallCard.js";
function shortenNumber(n: number): string {
@@ -65,7 +65,8 @@ interface Props {
type ContentGroup =
| { type: "text"; block: TextBlock; index: number }
- | { type: "tool_calls"; blocks: ToolCallBlock[]; index: number };
+ | { type: "tool_calls"; blocks: ToolCallBlock[]; index: number }
+ | { type: "image"; block: ImageBlock; index: number };
/** Extract domain + TLD from a hostname (e.g. "www.example.co.uk" → "example.co.uk"). */
function extractDomain(hostname: string): string {
@@ -191,7 +192,7 @@ export default function ChatMessage({ message, isStreaming, onRetry }: Props) {
<div className={`llm-chat-message-wrapper llm-chat-message-wrapper-${message.role}`}>
<div className={messageClasses}>
<div className="llm-chat-message-content">
- {message.role === "assistant" && hasBlockContent ? (
+ {hasBlockContent ? (
renderContentBlocks(message.content as ContentBlock[], isStreaming)
) : (
<MarkdownContent html={renderedContent || ""} isStreaming={isStreaming && message.role === "assistant"} />
@@ -253,6 +254,8 @@ function groupContentBlocks(blocks: ContentBlock[]): ContentGroup[] {
} else {
groups.push({ type: "tool_calls", blocks: [block], index: i });
}
+ } else if (block.type === "image") {
+ groups.push({ type: "image", block, index: i });
} else {
groups.push({ type: "text", block, index: i });
}
@@ -273,6 +276,21 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {
);
}
+ if (group.type === "image") {
+ return (
+ <a
+ key={group.index}
+ href={group.block.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="llm-chat-message-image"
+ title={group.block.title}
+ >
+ <img src={group.block.url} alt={group.block.title} />
+ </a>
+ );
+ }
+
return <ToolCallCard key={group.index} toolCalls={group.blocks.map((b) => b.toolCall)} />;
});
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
index 1fa74fe6af..e0a2c73516 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
@@ -27,8 +27,22 @@ export interface ToolCallBlock {
toolCall: ToolCall;
}
-/** An ordered content block in an assistant message. */
-export type ContentBlock = TextBlock | ToolCallBlock;
+/**
+ * An image attached to a user message, stored as a reference to a Trilium
+ * attachment (uploaded to the chat note). The server resolves the bytes from
+ * Becca before forwarding to the LLM provider.
+ */
+export interface ImageBlock {
+ type: "image";
+ attachmentId: string;
+ mime: string;
+ title: string;
+ /** URL for inline display in the UI (e.g. `api/attachments/<id>/image/<title>`). */
+ url: string;
+}
+
+/** An ordered content block in a chat message. */
+export type ContentBlock = TextBlock | ToolCallBlock | ImageBlock;
/**
* Extract the plain text from message content (works for both legacy string and block formats).
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 d85ad8f655..103d31c5e7 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -1,10 +1,37 @@
-import type { LlmCitation, LlmMessage, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
+import type { LlmCitation, LlmMessage, LlmMessagePart, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { getAvailableModels, streamChatCompletion } from "../../../services/llm_chat.js";
import { randomString } from "../../../services/utils.js";
-import type { ContentBlock, LlmChatContent, StoredMessage } from "./llm_chat_types.js";
+import type { ContentBlock, ImageBlock, LlmChatContent, StoredMessage } from "./llm_chat_types.js";
+
+/**
+ * Flatten a stored message's content into the wire format the server expects.
+ * Plain string content stays as-is; block-shaped content (with images) becomes
+ * an ordered array of text/image parts, with tool-call blocks stripped.
+ */
+function flattenToApiContent(content: string | ContentBlock[]): string | LlmMessagePart[] {
+ if (typeof content === "string") {
+ return content;
+ }
+ const parts: LlmMessagePart[] = [];
+ for (const block of content) {
+ if (block.type === "text") {
+ if (block.content) parts.push({ type: "text", text: block.content });
+ } else if (block.type === "image") {
+ parts.push({ type: "image", attachmentId: block.attachmentId, mime: block.mime });
+ }
+ // tool_call blocks belong to assistant history rendering only — they
+ // are reconstructed from the model's own tool-use turns and must not
+ // be re-sent as user/assistant content.
+ }
+ // Collapse to a string if there is no multimodal content — keeps backwards
+ // compatibility with providers/paths that haven't been touched.
+ if (parts.length === 0) return "";
+ if (parts.length === 1 && parts[0].type === "text") return parts[0].text;
+ return parts;
+}
export interface ModelOption extends LlmModelInfo {
costDescription?: string;
@@ -30,12 +57,16 @@ export interface UseLlmChatReturn {
streamingBlocks: ContentBlock[];
streamingThinking: string;
pendingCitations: LlmCitation[];
+ /** Images the user has attached but not yet sent. */
+ pendingAttachments: ImageBlock[];
availableModels: ModelOption[];
selectedModel: string;
enableWebSearch: boolean;
enableNoteTools: boolean;
enableExtendedThinking: boolean;
contextNoteId: string | undefined;
+ /** The chat note's ID — used as the upload target for attachments. */
+ chatNoteId: string | undefined;
lastPromptTokens: number;
messagesEndRef: RefObject<HTMLDivElement>;
scrollContainerRef: RefObject<HTMLDivElement>;
@@ -53,6 +84,10 @@ export interface UseLlmChatReturn {
setEnableExtendedThinking: (value: boolean) => void;
setContextNoteId: (noteId: string | undefined) => void;
setChatNoteId: (noteId: string | undefined) => void;
+ /** Append a freshly uploaded image to the pending-attachments list. */
+ addPendingAttachment: (attachment: ImageBlock) => void;
+ /** Remove a pending attachment by its attachment ID. */
+ removePendingAttachment: (attachmentId: string) => void;
// Actions
handleSubmit: (e: Event) => Promise<void>;
@@ -81,6 +116,7 @@ export function useLlmChat(
const [streamingBlocks, setStreamingBlocks] = useState<ContentBlock[]>([]);
const [streamingThinking, setStreamingThinking] = useState("");
const [pendingCitations, setPendingCitations] = useState<LlmCitation[]>([]);
+ const [pendingAttachments, setPendingAttachments] = useState<ImageBlock[]>([]);
const [availableModels, setAvailableModels] = useState<ModelOption[]>([]);
const [selectedModel, setSelectedModel] = useState<string>("");
const [enableWebSearch, setEnableWebSearch] = useState(true);
@@ -115,6 +151,15 @@ export function useLlmChat(
}, []);
const contextNoteIdRef = useRef(contextNoteId);
contextNoteIdRef.current = contextNoteId;
+ const pendingAttachmentsRef = useRef(pendingAttachments);
+ pendingAttachmentsRef.current = pendingAttachments;
+
+ const addPendingAttachment = useCallback((attachment: ImageBlock) => {
+ setPendingAttachments(prev => [...prev, attachment]);
+ }, []);
+ const removePendingAttachment = useCallback((attachmentId: string) => {
+ setPendingAttachments(prev => prev.filter(a => a.attachmentId !== attachmentId));
+ }, []);
// Wrapper to call onMessagesChange when messages update
const setMessages = useCallback((newMessages: StoredMessage[]) => {
@@ -248,10 +293,7 @@ export function useLlmChat(
const apiMessages: LlmMessage[] = conversation.map(m => ({
role: m.role,
- content: typeof m.content === "string" ? m.content : m.content
- .filter((b): b is ContentBlock & { type: "text" } => b.type === "text")
- .map(b => b.content)
- .join("")
+ content: flattenToApiContent(m.content)
}));
const selectedModelProvider = availableModels.find(m => m.id === selectedModel)?.provider;
@@ -466,15 +508,36 @@ export function useLlmChat(
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
- if (!input.trim() || isStreaming) return;
+ if (isStreaming) return;
+ const trimmedInput = input.trim();
+ const attachments = pendingAttachmentsRef.current;
+ if (!trimmedInput && attachments.length === 0) return;
+
+ // If there are attachments, build a block-shaped content array so the
+ // images travel alongside the text. Otherwise stay with the simple
+ // string form so existing chat history remains byte-identical.
+ let content: StoredMessage["content"];
+ if (attachments.length === 0) {
+ content = trimmedInput;
+ } else {
+ const blocks: ContentBlock[] = [];
+ if (trimmedInput) {
+ blocks.push({ type: "text", content: trimmedInput });
+ }
+ for (const att of attachments) {
+ blocks.push(att);
+ }
+ content = blocks;
+ }
const userMessage: StoredMessage = {
id: randomString(),
role: "user",
- content: input.trim(),
+ content,
createdAt: new Date().toISOString()
};
setInput("");
+ setPendingAttachments([]);
await runStream([...messages, userMessage]);
}, [input, isStreaming, messages, runStream]);
@@ -508,12 +571,14 @@ export function useLlmChat(
streamingBlocks,
streamingThinking,
pendingCitations,
+ pendingAttachments,
availableModels,
selectedModel,
enableWebSearch,
enableNoteTools,
enableExtendedThinking,
contextNoteId,
+ chatNoteId,
lastPromptTokens,
messagesEndRef,
scrollContainerRef,
@@ -529,6 +594,8 @@ export function useLlmChat(
setEnableExtendedThinking,
setContextNoteId,
setChatNoteId,
+ addPendingAttachment,
+ removePendingAttachment,
// Actions
handleSubmit,
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index 1564dd2ad2..ff7a72c8db 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -76,7 +76,15 @@ async function streamChat(req: Request, res: Response) {
const userMessages = messages.filter(m => m.role === "user");
if (userMessages.length === 1 && config.chatNoteId) {
try {
- await generateChatTitle(config.chatNoteId, userMessages[0].content);
+ const firstContent = userMessages[0].content;
+ // Multimodal content: title from the text parts only — image
+ // bytes are useless to the title model.
+ const firstText = typeof firstContent === "string"
+ ? firstContent
+ : firstContent.filter(p => p.type === "text").map(p => p.text).join("\n").trim();
+ if (firstText) {
+ await generateChatTitle(config.chatNoteId, firstText);
+ }
} catch (err) {
// Title generation is best-effort; don't fail the chat
log.error(`Failed to generate chat title: ${safeExtractMessageAndStackFromError(err)}`);
diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.ts
index 3e1393888f..00a892465d 100644
--- a/apps/server/src/services/llm/providers/anthropic.ts
+++ b/apps/server/src/services/llm/providers/anthropic.ts
@@ -1,9 +1,9 @@
-import { createAnthropic, type AnthropicProvider as AnthropicSDKProvider } from "@ai-sdk/anthropic";
-import { stepCountIs, streamText, type ModelMessage, type SystemModelMessage, type ToolSet } from "ai";
+import { type AnthropicProvider as AnthropicSDKProvider,createAnthropic } from "@ai-sdk/anthropic";
import type { LlmMessage } from "@triliumnext/commons";
+import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";
import type { LlmProviderConfig, StreamResult } from "../types.js";
-import { BaseProvider, buildModelList } from "./base_provider.js";
+import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";
/** Anthropic ephemeral prompt-caching breakpoint. */
const CACHE_CONTROL = { anthropic: { cacheControl: { type: "ephemeral" as const } } };
@@ -130,15 +130,18 @@ export class AnthropicProvider extends BaseProvider {
for (let i = 0; i < chatMessages.length; i++) {
const m = chatMessages[i];
const isLastBeforeNewTurn = i === chatMessages.length - 2;
- // Anthropic rejects empty text content blocks. Replace empty
- // content (e.g. tool-only assistant turns) with a placeholder
- // to preserve conversation flow.
- const content = m.content || "(tool use)";
- coreMessages.push({
- role: m.role as "user" | "assistant",
- content,
- ...(isLastBeforeNewTurn && { providerOptions: CACHE_CONTROL })
- });
+ // Anthropic rejects empty text content blocks. For purely-empty
+ // string content (e.g. tool-only assistant turns), substitute a
+ // placeholder so the turn still has a body.
+ const normalized: LlmMessage = (typeof m.content === "string" && !m.content)
+ ? { ...m, content: "(tool use)" }
+ : m;
+ const base = buildModelMessage(normalized);
+ coreMessages.push(
+ isLastBeforeNewTurn
+ ? { ...base, providerOptions: CACHE_CONTROL }
+ : base
+ );
}
return coreMessages;
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index e5cc6aec72..9bd144a674 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -3,11 +3,12 @@
* tool assembly, model pricing, and title generation.
*/
-import type { LlmMessage } from "@triliumnext/commons";
-import { generateText, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";
+import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";
+import { generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";
import yaml from "js-yaml";
import becca from "../../../becca/becca.js";
+import log from "../../log.js";
import { getSkillsSummary } from "../skills/index.js";
import { getNoteMeta,SYSTEM_PROMPT_LIMITS } from "../tools/helpers.js";
import { allToolRegistries } from "../tools/index.js";
@@ -43,6 +44,53 @@ function buildNoteHint(noteId: string): string | null {
].join("\n");
}
+/**
+ * Resolve a single LlmMessagePart to its AI SDK ModelMessage part form.
+ * For image parts, this reads the attachment bytes out of Becca; failures are
+ * logged and the part is dropped so the rest of the message still goes through.
+ */
+function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | null {
+ if (part.type === "text") {
+ return { type: "text", text: part.text };
+ }
+ // type === "image"
+ 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;
+ }
+ return {
+ type: "image",
+ image: attachment.getContent(),
+ mediaType: part.mime || attachment.mime
+ };
+}
+
+/**
+ * Build a single ModelMessage from an LlmMessage. Plain string content stays
+ * as-is; multimodal content is resolved into AI SDK text/image parts.
+ */
+export function buildModelMessage(m: LlmMessage): ModelMessage {
+ const role = m.role as "user" | "assistant";
+ if (typeof m.content === "string") {
+ return { role, content: m.content };
+ }
+ const resolved = m.content
+ .map(resolveMessagePart)
+ .filter((p): p is TextPart | ImagePart => p !== null);
+ // Assistant turns can only carry TextParts (per the AI SDK type), so
+ // strip any stray images — they only make sense on user turns anyway.
+ if (role === "assistant") {
+ const textOnly: TextPart[] = resolved.filter((p): p is TextPart => p.type === "text");
+ return { role: "assistant", content: textOnly };
+ }
+ return { role: "user", content: resolved };
+}
+
/**
* Build the model list with cost multipliers from a base model definition array.
*/
@@ -82,8 +130,11 @@ export abstract class BaseProvider implements LlmProvider {
protected buildSystemPrompt(messages: LlmMessage[], config: LlmProviderConfig): string | undefined {
const parts: string[] = [];
- // Base system prompt from config or messages
- const basePrompt = config.systemPrompt || messages.find(m => m.role === "system")?.content;
+ // Base system prompt from config or messages. System messages only ever
+ // carry string content — multimodal parts apply to user/assistant turns.
+ const systemMessage = messages.find(m => m.role === "system");
+ const messageSystemPrompt = typeof systemMessage?.content === "string" ? systemMessage.content : undefined;
+ const basePrompt = config.systemPrompt || messageSystemPrompt;
if (basePrompt) {
parts.push(basePrompt);
}
@@ -156,10 +207,7 @@ export abstract class BaseProvider implements LlmProvider {
* which is resilient against prompt injection.
*/
protected buildMessages(chatMessages: LlmMessage[]): ModelMessage[] {
- return chatMessages.map(m => ({
- role: m.role as "user" | "assistant",
- content: m.content
- }));
+ return chatMessages.map(m => buildModelMessage(m));
}
/**
@@ -186,9 +234,18 @@ export abstract class BaseProvider implements LlmProvider {
return chatMessages;
}
- return chatMessages.map((m, i) =>
- i === lastUserIndex ? { ...m, content: `${noteHint}\n\n${m.content}` } : m
- );
+ return chatMessages.map((m, i) => {
+ if (i !== lastUserIndex) return m;
+ if (typeof m.content === "string") {
+ return { ...m, content: `${noteHint}\n\n${m.content}` };
+ }
+ // For multimodal content, prepend the hint as a leading text part so
+ // any attached images still travel with the message.
+ return {
+ ...m,
+ content: [{ type: "text" as const, text: noteHint }, ...m.content]
+ };
+ });
}
/**
diff --git a/apps/server/src/services/llm/tools/note_tools.spec.ts b/apps/server/src/services/llm/tools/note_tools.spec.ts
index fdba7e753c..b38873ebad 100644
--- a/apps/server/src/services/llm/tools/note_tools.spec.ts
+++ b/apps/server/src/services/llm/tools/note_tools.spec.ts
@@ -127,8 +127,8 @@ describe("note_tools — write tools return post-write content", () => {
const newNote = buildNote({ id: "new1", type: "code", mime: "text/plain", content: "hello" });
withMutableContent(newNote, "hello");
- const noteService = (await import("../../notes.js")).default as { createNewNote: ReturnType<typeof vi.fn> };
- noteService.createNewNote.mockReturnValue({ note: newNote });
+ const noteService = (await import("../../notes.js")).default;
+ vi.mocked(noteService.createNewNote).mockReturnValue({ note: newNote } as ReturnType<typeof noteService.createNewNote>);
const result = getTool("create_note").execute({
parentNoteId: "parent1",
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index 69fde290f5..d8f1ec7572 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -4,11 +4,35 @@
*/
/**
- * A chat message in the conversation.
+ * Plain-text segment of a multimodal message.
+ */
+export interface LlmTextPart {
+ type: "text";
+ text: string;
+}
+
+/**
+ * Image segment of a multimodal message. The image is referenced by its
+ * Trilium attachment ID — the server loads the bytes from Becca before
+ * forwarding to the provider, so the wire stays small and we don't store
+ * base64 in chat history.
+ */
+export interface LlmImagePart {
+ type: "image";
+ attachmentId: string;
+ /** IANA media type (e.g. "image/png"). */
+ mime: string;
+}
+
+export type LlmMessagePart = LlmTextPart | LlmImagePart;
+
+/**
+ * A chat message in the conversation. `content` may be a plain string (the
+ * common case) or an ordered array of parts when the message includes images.
*/
export interface LlmMessage {
role: "user" | "assistant" | "system";
- content: string;
+ content: string | LlmMessagePart[];
}
/**