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

+5 -5
View File
@@ -312,8 +312,8 @@ export const AIMessageItem = memo(({
// Extract image URLs from content array
const imageUrls = contentArray
? contentArray
.filter(part => part.type === 'image_url')
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
.filter(part => part.type === 'image_url')
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
: [];
return (
@@ -321,7 +321,9 @@ export const AIMessageItem = memo(({
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words space-y-2">
{/* Render images first */}
{/* Render text content and attachments first */}
{userContent && <UserMessage content={userContent} />}
{/* Render images after text and attachments */}
{imageUrls.length > 0 && (
<div className="space-y-2">
{imageUrls.map((url, index) => (
@@ -349,8 +351,6 @@ export const AIMessageItem = memo(({
))}
</div>
)}
{/* Render text content */}
{userContent && <UserMessage content={userContent} />}
</div>
</div>
</div>
+11 -2
View File
@@ -44,6 +44,7 @@ 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
@@ -77,6 +78,7 @@ 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();
@@ -439,13 +441,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const modelToUse = providerModel.trim();
// Build message content from input and attached files
const messageContent = await buildMessageContent(input, attachedFiles, fs, tmpPath);
// Pass uploadFile function if user is logged in
const messageContent = await buildMessageContent(
input,
attachedFiles,
fs,
tmpPath,
user ? uploadFile : undefined
);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, uploadFile, user]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
+5 -2
View File
@@ -16,8 +16,11 @@ describe('UserMessage', () => {
render(<UserMessage content={content} />);
// When using string content, it should still work but won't separate file attachments
expect(screen.getByText(content)).toBeInTheDocument();
// When using string content, it should parse and separate file attachments
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
});
it('renders file attachment badges for single file with text parts', () => {
+58 -25
View File
@@ -1,4 +1,4 @@
import { FileText, File } from 'lucide-react';
import { Paperclip } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
@@ -18,21 +18,60 @@ export function UserMessage({ content }: UserMessageProps) {
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "Added file: /tmp/<filename>" patterns
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
// Matches the pattern anywhere in the text
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
// Process each content part and categorize as text or file
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
contentParts.forEach(part => {
const text = part.text.trim();
const match = text.match(filePattern);
// Find all file patterns in this text part
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
let match;
filePattern.lastIndex = 0; // Reset regex
while ((match = filePattern.exec(text)) !== null) {
fileMatches.push({
filepath: match[1], // "/tmp/filename.txt"
index: match.index,
length: match[0].length
});
}
if (match) {
// This is a file attachment
const filepath = match[1]; // "/tmp/filename.txt"
processedParts.push({ type: 'file', content: text, filepath });
if (fileMatches.length > 0) {
// Split text around file patterns and process each segment
let lastIndex = 0;
fileMatches.forEach((fileMatch) => {
// Add text before the file pattern
if (fileMatch.index > lastIndex) {
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
if (textBefore) {
processedParts.push({ type: 'text', content: textBefore });
}
}
// Add the file attachment badge (without showing "Added file:" text)
processedParts.push({
type: 'file',
content: '', // Empty - badge will show filename only
filepath: fileMatch.filepath
});
lastIndex = fileMatch.index + fileMatch.length;
});
// Add remaining text after the last file pattern
if (lastIndex < text.length) {
const textAfter = text.substring(lastIndex).trim();
if (textAfter) {
processedParts.push({ type: 'text', content: textAfter });
}
}
} else if (text) {
// This is regular text content
// No file patterns found, treat as regular text
processedParts.push({ type: 'text', content: text });
}
});
@@ -42,19 +81,6 @@ export function UserMessage({ content }: UserMessageProps) {
return null;
}
const getFileIcon = (filename: string) => {
const extension = filename.split('.').pop()?.toLowerCase();
// Return FileText icon for text-like files, File icon for others
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
if (extension && textExtensions.includes(extension)) {
return <FileText className="h-3 w-3" />;
}
return <File className="h-3 w-3" />;
};
const getFileName = (filepath: string) => {
return filepath.split('/').pop() || filepath;
};
@@ -63,18 +89,25 @@ export function UserMessage({ content }: UserMessageProps) {
<div className="space-y-2">
{processedParts.map((part, index) => {
if (part.type === 'text') {
// Only render text if it has content
if (!part.content.trim()) return null;
return (
<div key={index} className="whitespace-pre-wrap">
{part.content}
</div>
);
} else {
// Render file attachment badge (no "Added file:" text)
const filename = getFileName(part.filepath!);
return (
<div key={index} className="flex items-center gap-2">
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
{getFileIcon(filename)}
<span className="text-xs font-medium">{filename}</span>
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
<span className="flex-shrink-0">
<Paperclip className="h-3 w-3" />
</span>
<span className="text-xs font-medium truncate min-w-0" title={filename}>
{filename}
</span>
</Badge>
</div>
);
+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;
}
}
+12 -1
View File
@@ -24,6 +24,8 @@ 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();
@@ -48,6 +50,8 @@ 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);
@@ -231,7 +235,14 @@ export default function Index() {
const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId);
// Build message content from input and attached files
const messageContent = await buildMessageContent(prompt.trim(), attachedFiles, fs);
// Pass uploadFile function if user is logged in
const messageContent = await buildMessageContent(
prompt.trim(),
attachedFiles,
fs,
undefined,
user ? uploadFile : undefined
);
// Store the initial message in chat history using DotAI
const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`);