Don't upload images to Blossom

This commit is contained in:
Alex Gleason committed 2025-11-23 11:30:34 -06:00
1 parent e88b8c90d9
commit d2a8ee36f7
5 files changed
+39 -93

No files matched your search

+3 -6
View File
@@ -44,7 +44,6 @@ import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { useUploadFile } from '@/hooks/useUploadFile';
// Clean interfaces now handled by proper hooks
@@ -78,7 +77,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const { fs } = useFS();
const { git } = useGit();
const { user } = useCurrentUser();
const { mutateAsync: uploadFile } = useUploadFile();
const { models } = useProviderModels();
const { config } = useAppContext();
const { projectsPath, tmpPath, pluginsPath } = useFSPaths();
@@ -441,20 +439,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const modelToUse = providerModel.trim();
// Build message content from input and attached files
// Pass uploadFile function if user is logged in
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
input,
attachedFiles,
fs,
tmpPath,
user ? uploadFile : undefined
tmpPath
);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, uploadFile, user]);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
+17 -18
View File
@@ -9,42 +9,41 @@ type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenA
/**
* Builds message content from text input, image URLs, and attached files.
* Downloads image URLs to VFS and processes uploaded files.
*
*
* - All image formats are included in the message content for UI display
* - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API
* - All files are saved to VFS and get a text part with the path
*
* - Images are converted to base64-encoded data URLs for API consumption
*
* Returns content as either a string (for simple text) or an array of content parts.
*
*
* @param input - User text input that may contain image URLs
* @param attachedFiles - Array of files to attach
* @param fs - Filesystem instance for saving files
* @param tmpPath - Temporary directory path for file storage
* @param uploadFile - Optional upload function from useUploadFile hook for converting files to URLs
* @returns Promise resolving to message content (string or array of content parts)
*/
export async function buildMessageContent(
input: string,
attachedFiles: File[],
fs: JSRuntimeFS,
tmpPath = '/tmp',
uploadFile?: (file: File) => Promise<Array<[string, string] | string[]>>
tmpPath = '/tmp'
): Promise<string | ContentPart[]> {
const contentParts: ContentPart[] = [];
// Parse user input to detect image URLs and split into content parts
if (input.trim()) {
const parsedParts = parseImageUrls(input.trim());
// Process each part: download image URLs to VFS and add text parts with VFS paths
for (const part of parsedParts) {
if (part.type === 'image_url') {
// Download image to VFS and get the path
const result = await urlToFile(part.image_url.url, fs, tmpPath);
// Always add image_url part for UI display (all formats)
contentParts.push(part);
// Always add text part with VFS path so AI knows where the file is (can manipulate it)
if (result?.vfsPath) {
contentParts.push({
@@ -64,18 +63,18 @@ export async function buildMessageContent(
try {
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
type: 'text',
text: `Added file: ${savedPath}`
};
// For all image types, also add as image_url for UI display (if uploadFile available)
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = file.type.startsWith('image/');
if (isImage && uploadFile) {
if (isImage) {
try {
const imageUrl = await fileToUrl(file, uploadFile);
const imageUrl = await fileToUrl(file);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
@@ -83,10 +82,10 @@ export async function buildMessageContent(
}];
} catch (error) {
// If URL conversion fails, just use text part
console.warn('Failed to convert image to URL, using text part only:', error);
console.warn('Failed to convert image to base64, using text part only:', error);
}
}
return [textPart];
} catch (error) {
console.error('Failed to save file:', error);
@@ -98,7 +97,7 @@ export async function buildMessageContent(
});
const fileResults = await Promise.all(filePromises);
// Flatten the results (each file can return multiple parts)
for (const parts of fileResults) {
contentParts.push(...parts);
@@ -109,7 +108,7 @@ export async function buildMessageContent(
if (contentParts.length === 1 && contentParts[0].type === 'text') {
return contentParts[0].text;
}
// Return array for multiple parts or if contains image URLs
return contentParts;
}
+6 -31
View File
@@ -2,37 +2,12 @@ import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { generateUniqueFilename } from './fileUtils';
/**
* Converts a File to a URL string for API consumption.
* Tries useUploadFile first if available, otherwise falls back to data URL.
*
* Converts a File to a base64-encoded data URL for API consumption.
*
* @param file - The file to convert
* @param uploadFile - Optional upload function from useUploadFile hook
* @returns Promise resolving to URL string
* @returns Promise resolving to base64 data URL string
*/
export async function fileToUrl(
file: File,
uploadFile?: (file: File) => Promise<Array<[string, string] | string[]>>
): Promise<string> {
// Try useUploadFile first if available
if (uploadFile) {
try {
const tags = await uploadFile(file);
// Extract URL from NIP-94 compatible tags
// The first tag contains the URL
if (tags && tags.length > 0 && tags[0]) {
const firstTag = tags[0];
// Handle both tuple [string, string] and array string[] formats
if (Array.isArray(firstTag) && firstTag.length > 1) {
return firstTag[1] as string;
}
}
} catch (error) {
console.warn('Failed to upload file via useUploadFile, falling back to data URL:', error);
// Fall through to data URL fallback
}
}
// Fallback to data URL
export async function fileToUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
@@ -53,7 +28,7 @@ export async function fileToUrl(
* Converts a URL to a file saved in the VFS.
* Downloads an image from a URL and saves it to the VFS.
* Returns both the original URL (for API calls) and the VFS path (for reference).
*
*
* @param imageUrl - The image URL to download
* @param fs - Filesystem instance for saving files
* @param tmpPath - Temporary directory path for file storage
@@ -113,7 +88,7 @@ export async function urlToFile(
let filename = 'downloaded_image';
const urlPath = new URL(imageUrl).pathname;
const urlFilename = urlPath.split('/').pop();
if (urlFilename && /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(urlFilename)) {
filename = urlFilename;
} else {
+2 -7
View File
@@ -24,8 +24,6 @@ import { ArrowUp } from 'lucide-react';
import { useSeoMeta } from '@unhead/react';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { AppShowcase } from '@/components/AppShowcase';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useCurrentUser } from '@/hooks/useCurrentUser';
export default function Index() {
const { t } = useTranslation();
@@ -50,8 +48,6 @@ export default function Index() {
});
const isMobile = useIsMobile();
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const { user } = useCurrentUser();
const { mutateAsync: uploadFile } = useUploadFile();
const [isDragOver, setIsDragOver] = useState(false);
const [quillyError, setQuillyError] = useState<Error | null>(null);
@@ -235,13 +231,12 @@ export default function Index() {
const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId);
// Build message content from input and attached files
// Pass uploadFile function if user is logged in
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
prompt.trim(),
attachedFiles,
fs,
undefined,
user ? uploadFile : undefined
undefined
);
// Store the initial message in chat history using DotAI