add images to both VFS and API, update ChatPane UI

This commit is contained in:
lemonknowsall committed 2025-11-15 20:43:35 -08:00
1 parent 42637458c9
commit 653a7c0f0c
8 files changed
+339 -54

No files matched your search

+32 -1
View File
@@ -278,13 +278,44 @@ export class SessionManager {
template: config.systemPrompt,
});
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
return msgs.map(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
const filteredContent = msg.content.filter(part => {
if (part.type !== 'image_url') return true;
const imagePart = part as OpenAI.Chat.Completions.ChatCompletionContentPartImage;
const url = imagePart.image_url.url.toLowerCase();
// Keep only JPG/JPEG/PNG images
// Check file extension or data URL MIME type
return /\.(jpg|jpeg|png)(\?|$)/.test(url) ||
url.startsWith('data:image/jpeg') ||
url.startsWith('data:image/png') ||
url.startsWith('data:image/jpg');
});
return {
...msg,
content: filteredContent
};
}
return msg;
});
};
// Prepare messages for AI
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
// This ensures the UI shows all image types, but API only receives supported formats
messages = filterSupportedImages(messages);
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
model,
+67 -18
View File
@@ -2,66 +2,115 @@ import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { parseImageUrls } from './parseImageUrls';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl, urlToFile } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
/**
* 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
*
* 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'
tmpPath = '/tmp',
uploadFile?: (file: File) => Promise<Array<[string, string] | string[]>>
): 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());
contentParts.push(...parsedParts);
// 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({
type: 'text',
text: `Added file: ${result.vfsPath}`
});
}
} else {
contentParts.push(part);
}
}
}
// Process attached files and add as separate text parts
// Process attached files: save to VFS and add image_url for UI display (all image types)
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
return `Added file: ${savedPath}`;
// 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)
const isImage = file.type.startsWith('image/');
if (isImage && uploadFile) {
try {
const imageUrl = await fileToUrl(file, uploadFile);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
image_url: { url: imageUrl }
}];
} catch (error) {
// If URL conversion fails, just use text part
console.warn('Failed to convert image to URL, using text part only:', error);
}
}
return [textPart];
} catch (error) {
console.error('Failed to save file:', error);
return `Failed to save file: ${file.name}`;
return [{
type: 'text' as const,
text: `Failed to save file: ${file.name}`
}];
}
});
const fileResults = await Promise.all(filePromises);
// Add each file as a separate text part
fileResults.forEach(fileResult => {
contentParts.push({
type: 'text',
text: fileResult
});
});
// Flatten the results (each file can return multiple parts)
for (const parts of fileResults) {
contentParts.push(...parts);
}
}
// Return as string if single text part, otherwise return array
const hasImageUrls = contentParts.some(part => part.type === 'image_url');
if (contentParts.length > 1 || hasImageUrls) {
return contentParts;
}
if (contentParts.length === 1 && contentParts[0].type === 'text') {
return contentParts[0].text;
}
// Return array for multiple parts or if contains image URLs
return contentParts;
}
+149
View File
@@ -0,0 +1,149 @@
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.
*
* @param file - The file to convert
* @param uploadFile - Optional upload function from useUploadFile hook
* @returns Promise resolving to 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
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject(new Error('Failed to read file as data URL'));
}
};
reader.onerror = () => {
reject(new Error('Failed to read file'));
};
reader.readAsDataURL(file);
});
}
/**
* 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
* @returns Promise resolving to object with originalUrl and vfsPath, or null if download fails
*/
export async function urlToFile(
imageUrl: string,
fs: JSRuntimeFS,
tmpPath = '/tmp'
): Promise<{ originalUrl: string; vfsPath: string } | null> {
try {
// Handle data URLs - extract and save them
if (imageUrl.startsWith('data:image/')) {
const [header, base64Data] = imageUrl.split(',');
if (!base64Data) {
console.warn('Invalid data URL format:', imageUrl);
return null;
}
// Extract MIME type and extension from header
const mimeMatch = header.match(/data:image\/([^;]+)/);
const mimeType = mimeMatch ? mimeMatch[1] : 'png';
const extension = mimeType === 'jpeg' ? 'jpg' : mimeType;
// Generate filename
const filename = `downloaded_image_${Date.now()}.${extension}`;
const uniqueFilename = await generateUniqueFilename(fs, tmpPath, filename);
const vfsPath = `${tmpPath}/${uniqueFilename}`;
// Convert base64 to Uint8Array
const binaryString = atob(base64Data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Write to VFS
await fs.writeFile(vfsPath, bytes);
return { originalUrl: imageUrl, vfsPath };
}
// Handle HTTP/HTTPS URLs
const response = await fetch(imageUrl, {
method: 'GET',
headers: {
'Accept': 'image/*',
},
});
if (!response.ok) {
console.warn(`Failed to download image from ${imageUrl}: ${response.status} ${response.statusText}`);
return null;
}
// Determine filename from URL or Content-Type
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 {
// Try to get extension from Content-Type
const contentType = response.headers.get('Content-Type');
if (contentType?.startsWith('image/')) {
const mimeType = contentType.split('/')[1];
const extension = mimeType === 'jpeg' ? 'jpg' : mimeType;
filename = `downloaded_image_${Date.now()}.${extension}`;
} else {
filename = `downloaded_image_${Date.now()}.png`;
}
}
// Sanitize filename
const sanitizedFilename = filename.replace(/\s+/g, '_');
const uniqueFilename = await generateUniqueFilename(fs, tmpPath, sanitizedFilename);
const vfsPath = `${tmpPath}/${uniqueFilename}`;
// Read response as array buffer and convert to Uint8Array
const arrayBuffer = await response.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
// Write to VFS
await fs.writeFile(vfsPath, uint8Array);
return { originalUrl: imageUrl, vfsPath };
} catch (error) {
console.warn(`Error downloading image from ${imageUrl}:`, error);
return null;
}
}