Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): add support for basic file attachments

Elian Dorand63c3d297447
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index bc884b8dcd..1609e9ca9b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1814,10 +1814,10 @@
"add_provider": "Add AI Provider",
"stop": "Stop",
"retry": "Retry",
- "attach_file": "Attach image or PDF",
+ "attach_file": "Attach image, PDF, or text file",
"remove_attachment": "Remove attachment",
"attachment_upload_failed": "Failed to upload \"{{name}}\".",
- "attachment_unsupported_type": "\"{{name}}\" isn't a supported attachment type. Use PNG, JPEG, GIF, WebP, or PDF."
+ "attachment_unsupported_type": "\"{{name}}\" isn't a supported attachment type. Use an image (PNG, JPEG, GIF, WebP), a PDF, or a text/source file."
},
"sidebar_chat": {
"title": "AI Chat",
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 36a10d356c..bd8c82c6f1 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -16,14 +16,39 @@ 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 { FileBlock, ImageBlock } from "./llm_chat_types.js";
+import type { FileBlock, ImageBlock, TextFileBlock } from "./llm_chat_types.js";
import type { AttachmentBlock, 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"];
-/** Non-image MIME types we accept. PDFs are supported natively by Anthropic, OpenAI, and Google. */
-const ACCEPTED_FILE_TYPES = ["application/pdf"];
-const ACCEPTED_UPLOAD_TYPES = [...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_FILE_TYPES];
+/** Binary file MIME types we accept (provider-side handling). PDFs are supported by Anthropic, OpenAI, Google. */
+const ACCEPTED_BINARY_FILE_TYPES = ["application/pdf"];
+/**
+ * File extensions we treat as text. The browser often reports an empty or
+ * generic MIME for source code, so extension-based detection is the practical
+ * approach. The server decodes the bytes as UTF-8 and inlines them as text.
+ */
+const ACCEPTED_TEXT_EXTENSIONS = [
+ ".txt", ".md", ".markdown", ".rst", ".log",
+ ".csv", ".tsv",
+ ".json", ".yaml", ".yml", ".xml", ".toml", ".ini", ".env",
+ ".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs",
+ ".py", ".rb", ".go", ".rs", ".c", ".cc", ".cpp", ".h", ".hpp",
+ ".java", ".kt", ".swift", ".php", ".lua", ".pl", ".scala",
+ ".sh", ".bash", ".zsh", ".sql",
+ ".html", ".htm", ".css", ".scss", ".vue", ".svelte"
+];
+
+/** Best-effort classification of an uploaded file. */
+type UploadKind = "image" | "binary_file" | "text_file" | null;
+function classifyUpload(file: File): UploadKind {
+ if (ACCEPTED_IMAGE_TYPES.includes(file.type)) return "image";
+ if (ACCEPTED_BINARY_FILE_TYPES.includes(file.type)) return "binary_file";
+ if (file.type.startsWith("text/")) return "text_file";
+ const lowerName = file.name.toLowerCase();
+ if (ACCEPTED_TEXT_EXTENSIONS.some(ext => lowerName.endsWith(ext))) return "text_file";
+ return null;
+}
const READ_ONLY_LOCK = "llm-chat-streaming";
@@ -75,9 +100,10 @@ function parseAttachmentIdFromUploadUrl(url: string): string | null {
* Upload a file as an attachment to the chat note and return a block describing
* it. The server's `notes/{id}/attachments/upload` endpoint sorts images and
* non-images into different attachment roles and returns different URL shapes;
- * we unify them back into a typed block here.
+ * we unify them back into a typed block here based on the client's
+ * pre-classification.
*/
-async function uploadFileAsAttachment(noteId: string, file: File): Promise<AttachmentBlock | null> {
+async function uploadFileAsAttachment(noteId: string, file: File, kind: UploadKind): Promise<AttachmentBlock | null> {
let detail: string | undefined;
try {
const result = await server.upload(
@@ -87,7 +113,7 @@ async function uploadFileAsAttachment(noteId: string, file: File): Promise<Attac
if (result?.uploaded && result.url) {
const attachmentId = parseAttachmentIdFromUploadUrl(result.url);
if (attachmentId) {
- if (ACCEPTED_IMAGE_TYPES.includes(file.type)) {
+ if (kind === "image") {
return {
type: "image",
attachmentId,
@@ -96,6 +122,15 @@ async function uploadFileAsAttachment(noteId: string, file: File): Promise<Attac
url: result.url
} satisfies ImageBlock;
}
+ if (kind === "text_file") {
+ return {
+ type: "text_file",
+ attachmentId,
+ mime: file.type || "text/plain",
+ title: file.name,
+ url: result.url
+ } satisfies TextFileBlock;
+ }
return {
type: "file",
attachmentId,
@@ -176,14 +211,15 @@ export default function ChatInputBar({
// Always-fresh submit handler for the editor's enter listener.
const submitRef = useRef<(e: Event) => void>(() => {});
- /** Upload an image or PDF to the chat note and add the result to pending attachments. */
+ /** Upload an image, PDF, or text file to the chat note and add the result to pending attachments. */
const uploadFile = useCallback(async (file: File) => {
if (!chat.chatNoteId) return;
- if (!ACCEPTED_UPLOAD_TYPES.includes(file.type)) {
+ const kind = classifyUpload(file);
+ if (!kind) {
toast.showError(t("llm_chat.attachment_unsupported_type", { name: file.name }));
return;
}
- const block = await uploadFileAsAttachment(chat.chatNoteId, file);
+ const block = await uploadFileAsAttachment(chat.chatNoteId, file, kind);
if (block) {
chat.addPendingAttachment(block);
}
@@ -205,9 +241,10 @@ export default function ChatInputBar({
if (!items) return;
const pastedFiles: File[] = [];
for (const item of Array.from(items)) {
- if (item.kind === "file" && ACCEPTED_UPLOAD_TYPES.includes(item.type)) {
- const file = item.getAsFile();
- if (file) pastedFiles.push(file);
+ if (item.kind !== "file") continue;
+ const file = item.getAsFile();
+ if (file && classifyUpload(file)) {
+ pastedFiles.push(file);
}
}
if (pastedFiles.length === 0) return;
@@ -361,7 +398,7 @@ export default function ChatInputBar({
<img src={att.url} alt={att.title} />
) : (
<div className="llm-chat-attachment-file">
- <span className="bx bxs-file-pdf llm-chat-attachment-file-icon" />
+ <span className={`bx ${att.type === "file" ? "bxs-file-pdf" : "bxs-file-blank"} llm-chat-attachment-file-icon`} />
<span className="llm-chat-attachment-file-name">{att.title}</span>
</div>
)}
@@ -414,7 +451,7 @@ export default function ChatInputBar({
<input
ref={fileInputRef}
type="file"
- accept={ACCEPTED_UPLOAD_TYPES.join(",")}
+ accept={[...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_BINARY_FILE_TYPES, ...ACCEPTED_TEXT_EXTENSIONS].join(",")}
multiple
onChange={handleFilePickerChange}
style={{ display: "none" }}
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 43483fd06e..2b48a6ff25 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, type FileBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type ToolCallBlock } from "./llm_chat_types.js";
+import { type ContentBlock, type FileBlock, getMessageText, type ImageBlock, type StoredMessage, type TextBlock, type TextFileBlock, type ToolCallBlock } from "./llm_chat_types.js";
import ToolCallCard from "./ToolCallCard.js";
function shortenNumber(n: number): string {
@@ -67,7 +67,8 @@ type ContentGroup =
| { type: "text"; block: TextBlock; index: number }
| { type: "tool_calls"; blocks: ToolCallBlock[]; index: number }
| { type: "image"; block: ImageBlock; index: number }
- | { type: "file"; block: FileBlock; index: number };
+ | { type: "file"; block: FileBlock; index: number }
+ | { type: "text_file"; block: TextFileBlock; index: number };
/** Extract domain + TLD from a hostname (e.g. "www.example.co.uk" → "example.co.uk"). */
function extractDomain(hostname: string): string {
@@ -259,6 +260,8 @@ function groupContentBlocks(blocks: ContentBlock[]): ContentGroup[] {
groups.push({ type: "image", block, index: i });
} else if (block.type === "file") {
groups.push({ type: "file", block, index: i });
+ } else if (block.type === "text_file") {
+ groups.push({ type: "text_file", block, index: i });
} else {
groups.push({ type: "text", block, index: i });
}
@@ -294,7 +297,8 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {
);
}
- if (group.type === "file") {
+ if (group.type === "file" || group.type === "text_file") {
+ const icon = group.type === "file" ? "bxs-file-pdf" : "bxs-file-blank";
return (
<a
key={group.index}
@@ -304,7 +308,7 @@ function renderContentBlocks(blocks: ContentBlock[], isStreaming?: boolean) {
className="llm-chat-message-file"
title={group.block.title}
>
- <span className="bx bxs-file-pdf" />
+ <span className={`bx ${icon}`} />
<span className="llm-chat-message-file-name">{group.block.title}</span>
</a>
);
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 898273db2e..e27069ccb0 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
@@ -55,8 +55,23 @@ export interface FileBlock {
url: string;
}
+/**
+ * A text-based file attached to a user message (e.g. `.md`, `.json`, source
+ * code). The server decodes the UTF-8 content and inlines it as a text part,
+ * so the LLM sees the file contents directly — works on every provider but
+ * inflates the prompt by the file size in tokens.
+ */
+export interface TextFileBlock {
+ type: "text_file";
+ attachmentId: string;
+ mime: string;
+ title: string;
+ /** URL pointing back at the attachment's note view. */
+ url: string;
+}
+
/** An ordered content block in a chat message. */
-export type ContentBlock = TextBlock | ToolCallBlock | ImageBlock | FileBlock;
+export type ContentBlock = TextBlock | ToolCallBlock | ImageBlock | FileBlock | TextFileBlock;
/**
* 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 5550aa75f9..5804ac30b7 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -4,10 +4,10 @@ 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, FileBlock, ImageBlock, LlmChatContent, StoredMessage } from "./llm_chat_types.js";
+import type { ContentBlock, FileBlock, ImageBlock, LlmChatContent, StoredMessage, TextFileBlock } from "./llm_chat_types.js";
/** A user-supplied attachment waiting to be sent with the next message. */
-export type AttachmentBlock = ImageBlock | FileBlock;
+export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;
/**
* Flatten a stored message's content into the wire format the server expects.
@@ -26,6 +26,8 @@ function flattenToApiContent(content: string | ContentBlock[]): string | LlmMess
parts.push({ type: "image", attachmentId: block.attachmentId, mime: block.mime });
} else if (block.type === "file") {
parts.push({ type: "file", attachmentId: block.attachmentId, mime: block.mime, filename: block.title });
+ } else if (block.type === "text_file") {
+ parts.push({ type: "text_attachment", attachmentId: block.attachmentId, filename: block.title });
}
// tool_call blocks belong to assistant history rendering only — they
// are reconstructed from the model's own tool-use turns and must not
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index d3154f161f..3f5d8ffa8c 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -4,6 +4,7 @@
*/
import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";
+import { decodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";
import { type FilePart, generateText, type ImagePart, type LanguageModel, type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type TextPart, type ToolSet } from "ai";
import yaml from "js-yaml";
@@ -46,9 +47,10 @@ function buildNoteHint(noteId: string): string | null {
/**
* Resolve a single LlmMessagePart to its AI SDK ModelMessage part form.
- * For image/file 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.
+ * For image/file parts, this reads the attachment bytes out of Becca. Text
+ * attachments are decoded as UTF-8 and emitted as a labelled TextPart so the
+ * file's content travels inline (works across all providers). Failures are
+ * logged and the part is dropped so the rest of the message still goes through.
*/
function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | FilePart | null {
if (part.type === "text") {
@@ -70,12 +72,23 @@ function resolveMessagePart(part: LlmMessagePart): TextPart | ImagePart | FilePa
mediaType: part.mime || attachment.mime
};
}
- // type === "file"
+ if (part.type === "file") {
+ return {
+ type: "file",
+ data: attachment.getContent(),
+ 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(attachment.getContent());
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>`
};
}
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index d8fdea9fcb..8c17eec73e 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -37,7 +37,19 @@ export interface LlmFilePart {
filename: string;
}
-export type LlmMessagePart = LlmTextPart | LlmImagePart | LlmFilePart;
+/**
+ * Text-file segment of a multimodal message (e.g. a `.md`, `.json`, source
+ * code). Unlike `LlmFilePart`, the server inlines the decoded UTF-8 content
+ * as a plain `TextPart` so it works with every provider regardless of file
+ * upload support — the trade-off is that large files inflate token usage.
+ */
+export interface LlmTextAttachmentPart {
+ type: "text_attachment";
+ attachmentId: string;
+ filename: string;
+}
+
+export type LlmMessagePart = LlmTextPart | LlmImagePart | LlmFilePart | LlmTextAttachmentPart;
/**
* A chat message in the conversation. `content` may be a plain string (the