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
refactor(llm): extract attachments to separate module
Elian Doran1e755b44f5f1
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 5826f0c064..9dc171256f 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -7,8 +7,6 @@ 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";@@ -16,40 +14,9 @@ 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, TextFileBlock } from "./llm_chat_types.js";import { retryImageOnError } from "./retry_image.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"];-/** 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;-}+import { useChatAttachments } from "./useChatAttachments.js";+import type { UseLlmChatReturn } from "./useLlmChat.js";const READ_ONLY_LOCK = "llm-chat-streaming";@@ -84,73 +51,6 @@ function formatTokenCount(tokens: number): string {return tokens.toLocaleString();}-/**- * Extract the Trilium attachment ID from one of the URLs returned by- * `notes/{id}/attachments/upload`. Image roles return `api/attachments/<id>/image/<title>`;- * file roles return `#root/<noteId>?viewMode=attachments&attachmentId=<id>`.- */-function parseAttachmentIdFromUploadUrl(url: string): string | null {- const imageMatch = url.match(/attachments\/([^/]+)\/image\//);- if (imageMatch) return imageMatch[1];- const fileMatch = url.match(/attachmentId=([^&]+)/);- if (fileMatch) return fileMatch[1];- return 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 based on the client's- * pre-classification.- */-async function uploadFileAsAttachment(noteId: string, file: File, kind: UploadKind): Promise<AttachmentBlock | 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) {- const attachmentId = parseAttachmentIdFromUploadUrl(result.url);- if (attachmentId) {- if (kind === "image") {- return {- type: "image",- attachmentId,- mime: file.type,- title: file.name,- 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,- mime: file.type,- title: file.name,- url: result.url- } satisfies FileBlock;- }- }- detail = result?.message;- } catch (e) {- detail = e instanceof Error ? e.message : undefined;- }-- const base = t("llm_chat.attachment_upload_failed", { name: file.name });- toast.showError(detail ? `${base} ${detail}` : base);- return null;-}-/*** Convert CKEditor HTML into plain text suitable for an LLM prompt.*@@ -208,77 +108,11 @@ 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>(() => {});- // Always-fresh paste handler for the DOM listener registered once in- // `onInitialized` — the listener calls through this ref so it picks up- // dependency changes (e.g. `chat.chatNoteId` being set after first render).- const pasteHandlerRef = useRef<(e: ClipboardEvent) => void>(() => {});-- /** 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;- 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, kind);- 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 pastedFiles: File[] = [];- for (const item of Array.from(items)) {- if (item.kind !== "file") continue;- const file = item.getAsFile();- if (file && classifyUpload(file)) {- pastedFiles.push(file);- }- }- if (pastedFiles.length === 0) return;- // Stop CKEditor from also pasting the file (e.g. an image as a base64- // data URL) — we want it as an attachment, not embedded markup.- e.preventDefault();- e.stopPropagation();- for (const file of pastedFiles) {- await uploadFile(file);- }- }, [uploadFile]);- pasteHandlerRef.current = handlePaste;-- 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();- }- }, []);+ // Clipboard / drag-drop / file-picker upload management.+ const attachments = useChatAttachments(chat);// CKEditor's ReferenceLink plugin calls back into the parent component to// resolve a note's title from its href.@@ -389,8 +223,8 @@ export default function ChatInputBar({<formclassName="llm-chat-input-form"onSubmit={handleSubmit}- onDrop={handleDrop}- onDragOver={handleDragOver}+ onDrop={attachments.handleDrop}+ onDragOver={attachments.handleDragOver}>{chat.pendingAttachments.length > 0 && (<div className="llm-chat-attachments">@@ -456,17 +290,17 @@ export default function ChatInputBar({const editable = editor.editing.view.getDomRoot();editable?.addEventListener("paste",- (e) => pasteHandlerRef.current(e as ClipboardEvent),+ (e) => attachments.pasteHandlerRef.current(e as ClipboardEvent),{ capture: true });}}/><input- ref={fileInputRef}+ ref={attachments.fileInputRef}type="file"- accept={[...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_BINARY_FILE_TYPES, ...ACCEPTED_TEXT_EXTENSIONS].join(",")}+ accept={attachments.acceptAttr}multiple- onChange={handleFilePickerChange}+ onChange={attachments.handleFilePickerChange}style={{ display: "none" }}/><div className="llm-chat-options">@@ -560,7 +394,7 @@ export default function ChatInputBar({<ActionButtonicon="bx bx-paperclip"text={t("llm_chat.attach_file")}- onClick={() => fileInputRef.current?.click()}+ onClick={attachments.openFilePicker}disabled={chat.isStreaming || !chat.chatNoteId}className="llm-chat-attach-btn"/>diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useChatAttachments.ts b/apps/client/src/widgets/type_widgets/llm_chat/useChatAttachments.tsnew file mode 100644index 0000000000..6b2b5493e1--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/useChatAttachments.ts@@ -0,0 +1,220 @@+import { RefObject } from "preact";+import { useCallback, useRef } from "preact/hooks";++import { t } from "../../../services/i18n.js";+import server from "../../../services/server.js";+import toast from "../../../services/toast.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"];+/** 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"+];++/** Joined `accept=` value for the hidden `<input type="file">` element. */+const ACCEPT_ATTR = [...ACCEPTED_IMAGE_TYPES, ...ACCEPTED_BINARY_FILE_TYPES, ...ACCEPTED_TEXT_EXTENSIONS].join(",");++/** 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;+}++/**+ * Extract the Trilium attachment ID from one of the URLs returned by+ * `notes/{id}/attachments/upload`. Image roles return `api/attachments/<id>/image/<title>`;+ * file roles return `#root/<noteId>?viewMode=attachments&attachmentId=<id>`.+ */+function parseAttachmentIdFromUploadUrl(url: string): string | null {+ const imageMatch = url.match(/attachments\/([^/]+)\/image\//);+ if (imageMatch) return imageMatch[1];+ const fileMatch = url.match(/attachmentId=([^&]+)/);+ if (fileMatch) return fileMatch[1];+ return 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 based on the client's+ * pre-classification.+ */+async function uploadFileAsAttachment(noteId: string, file: File, kind: UploadKind): Promise<AttachmentBlock | 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) {+ const attachmentId = parseAttachmentIdFromUploadUrl(result.url);+ if (attachmentId) {+ if (kind === "image") {+ return {+ type: "image",+ attachmentId,+ mime: file.type,+ title: file.name,+ 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,+ mime: file.type,+ title: file.name,+ url: result.url+ } satisfies FileBlock;+ }+ }+ detail = result?.message;+ } catch (e) {+ detail = e instanceof Error ? e.message : undefined;+ }++ const base = t("llm_chat.attachment_upload_failed", { name: file.name });+ toast.showError(detail ? `${base} ${detail}` : base);+ return null;+}++export interface UseChatAttachmentsReturn {+ /** Ref to plug into the hidden `<input type="file">`. */+ fileInputRef: RefObject<HTMLInputElement>;+ /** Value for the `accept` attribute of the hidden file input. */+ acceptAttr: string;+ /**+ * Always-fresh paste handler. The DOM `paste` listener on CKEditor is+ * registered once when the editor mounts, but `chat.chatNoteId` arrives+ * later via a parent useEffect — registering through this ref means the+ * listener always reads the current closure.+ */+ pasteHandlerRef: { current: (e: ClipboardEvent) => void };+ /** Programmatically open the file picker — wire to the attach button. */+ openFilePicker: () => void;+ /** `onChange` handler for the hidden file input. */+ handleFilePickerChange: (e: Event) => Promise<void>;+ /** `onDrop` handler for the form element. */+ handleDrop: (e: DragEvent) => Promise<void>;+ /** `onDragOver` handler for the form element (required for `onDrop` to fire). */+ handleDragOver: (e: DragEvent) => void;+}++/**+ * Manages clipboard / drag-drop / file-picker uploads for the chat input. Each+ * accepted file is uploaded as an attachment of the current chat note and+ * appended to the chat's pending-attachments list — the parent component just+ * wires the returned handlers into its JSX.+ */+export function useChatAttachments(chat: UseLlmChatReturn): UseChatAttachmentsReturn {+ const fileInputRef = useRef<HTMLInputElement>(null);+ const pasteHandlerRef = useRef<(e: ClipboardEvent) => void>(() => {});++ const uploadFile = useCallback(async (file: File) => {+ if (!chat.chatNoteId) return;+ 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, kind);+ 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 pastedFiles: File[] = [];+ for (const item of Array.from(items)) {+ if (item.kind !== "file") continue;+ const file = item.getAsFile();+ if (file && classifyUpload(file)) {+ pastedFiles.push(file);+ }+ }+ if (pastedFiles.length === 0) return;+ // Stop CKEditor from also pasting the file (e.g. an image as a base64+ // data URL) — we want it as an attachment, not embedded markup.+ e.preventDefault();+ e.stopPropagation();+ for (const file of pastedFiles) {+ await uploadFile(file);+ }+ }, [uploadFile]);+ pasteHandlerRef.current = handlePaste;++ 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();+ }+ }, []);++ const openFilePicker = useCallback(() => {+ fileInputRef.current?.click();+ }, []);++ return {+ fileInputRef,+ acceptAttr: ACCEPT_ATTR,+ pasteHandlerRef,+ openFilePicker,+ handleFilePickerChange,+ handleDrop,+ handleDragOver+ };+}