Merge branch 'parseImageURLs' into 'main'

Recognize Image URLs

See merge request soapbox-pub/shakespeare!71
This commit is contained in:
Alex Gleason committed 2025-11-23 17:57:24 +00:00
commit b7a55f7fd7
14 files changed
+690 -138

No files matched your search

+80 -7
View File
@@ -7,6 +7,8 @@ import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
import { isEmptyMessage } from '@/lib/isEmptyMessage';
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import * as DialogPrimitive from '@radix-ui/react-dialog';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
@@ -26,6 +28,7 @@ export const AIMessageItem = memo(({
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const { displayTheme } = useTheme();
// Get content to display
@@ -295,20 +298,90 @@ export const AIMessageItem = memo(({
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
// Extract text and image parts from message content
const contentArray = Array.isArray(message.content) ? message.content : null;
const textParts = contentArray
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: [];
const userContent = typeof message.content === 'string'
? message.content
: Array.isArray(message.content)
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: textParts.length > 0
? textParts.map(part => part.text).join('\n')
: '';
// 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)
: [];
return (
<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">
<UserMessage content={userContent} />
<>
<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 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) => (
<div
key={index}
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => setExpandedImageUrl(url)}
>
<img
src={url}
alt={`User uploaded image ${index + 1}`}
className="max-w-full h-auto max-h-96 object-contain"
loading="lazy"
onError={(e) => {
// Fallback if image fails to load
const target = e.target as HTMLImageElement;
target.style.display = 'none';
const fallback = document.createElement('div');
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
fallback.textContent = `Image failed to load: ${url}`;
target.parentElement?.appendChild(fallback);
}}
/>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
{/* Image expansion dialog */}
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
<DialogPortal>
<DialogOverlay className="bg-black/95" />
<DialogPrimitive.Content
className={cn(
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
"data-[state=open]:animate-in data-[state=closed]:animate-out",
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
)}
onPointerDownOutside={() => setExpandedImageUrl(null)}
onEscapeKeyDown={() => setExpandedImageUrl(null)}
>
{expandedImageUrl && (
<div className="relative flex items-center justify-center">
<img
src={expandedImageUrl}
alt="Expanded image"
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
/>
</div>
)}
</DialogPrimitive.Content>
</DialogPortal>
</Dialog>
</>
);
}
+9 -36
View File
@@ -41,11 +41,11 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
// Clean interfaces now handled by proper hooks
@@ -456,45 +456,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const modelToUse = providerModel.trim();
// Build message content as text parts
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
// Add user input as text part if present
if (input.trim()) {
contentParts.push({
type: 'text',
text: input.trim()
});
}
// Process attached files and add as separate text parts
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file, tmpPath);
return `Added file: ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `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
});
});
}
// Build message content from input and attached files
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
input,
attachedFiles,
fs,
tmpPath
);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
+33 -23
View File
@@ -3,9 +3,10 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Save, Loader2 } from 'lucide-react';
import { Save, Loader2, ImageOff } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
import { isMediaFile } from '@/lib/fileUtils';
interface FileEditorProps {
filePath: string;
@@ -93,6 +94,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
// Get git status for the current file
const currentFileGitStatus = getFileGitStatus(filePath);
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
const isMedia = isMediaFile(filePath);
return (
<div className="h-full flex flex-col">
@@ -100,32 +102,36 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<div className="flex items-center justify-between">
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
<div className="flex items-center space-x-1 sm:space-x-2">
{hasChanges && (
{hasChanges && !isMedia && (
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
)}
<Button
onClick={handleSave}
disabled={!hasChanges || isSaving || isLoading}
size="sm"
className="focus-ring"
>
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
{!isMedia && (
<Button
onClick={handleSave}
disabled={!hasChanges || isSaving || isLoading}
size="sm"
className="focus-ring"
>
{isSaving ? (
<>
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
<span className="hidden sm:inline">{t('saving')}</span>
</>
) : (
<>
<Save className="sm:mr-2 h-4 w-4" />
<span className="hidden sm:inline">{t('save')}</span>
</>
)}
</Button>
)}
</div>
</div>
<div className="text-xs text-muted-foreground mt-1">
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
{!isMedia && (
<div className="text-xs text-muted-foreground mt-1">
{t('languageLabel')}: {getLanguageFromPath(filePath)}
</div>
)}
</CardHeader>
<CardContent className="flex-1 p-0">
@@ -133,6 +139,10 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
<div className="flex items-center justify-center h-full">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
) : isMedia ? (
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
<ImageOff className="h-16 w-16 text-muted-foreground" />
</div>
) : (
<Textarea
value={editedContent}
@@ -32,6 +32,7 @@ import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
interface PreviewPaneProps {
projectId: string;
@@ -130,6 +131,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
// Skip loading media files - they can't be edited as text
if (isMediaFile(filePath)) {
setFileContent('');
setIsLoading(false);
return;
}
setIsLoading(true);
try {
const content = await projectsManager.readFile(projectId, filePath);
+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>
);
+4 -1
View File
@@ -114,7 +114,10 @@ export function useAIChat({
}, [projectId]);
// Actions
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
const sendMessage = useCallback(async (
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
providerModel: string
) => {
try {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
+21
View File
@@ -156,4 +156,25 @@ describe('SessionManager', () => {
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
expect(updatedSession?.messages[0].role).toBe('user');
});
it('should track when images are not supported and strip them on subsequent requests', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
// Load a session
const session = await sessionManager.loadSession(projectId, tools, customTools);
// Initially, images should not be marked as unsupported
expect(session.imagesNotSupported).toBeUndefined();
// Simulate marking images as not supported (this would happen after an API error)
session.imagesNotSupported = true;
// Verify the flag is set
expect(session.imagesNotSupported).toBe(true);
// On subsequent requests, the SessionManager should proactively strip images
// This prevents retrying with images on every message/tool call
});
});
+121 -7
View File
@@ -40,6 +40,7 @@ export interface SessionState {
abortController?: AbortController;
totalCost?: number; // Total cost in USD for this session
lastInputTokens?: number; // Input tokens from the last AI request
imagesNotSupported?: boolean; // Track if this session's model doesn't support images
}
export interface SessionManagerEvents {
@@ -187,7 +188,11 @@ export class SessionManager {
/**
* Send a message and start AI generation
*/
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
async sendMessage(
projectId: string,
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
providerModel: string
): Promise<void> {
const session = this.sessions.get(projectId);
if (!session || session.isLoading) return;
@@ -274,10 +279,73 @@ 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;
});
};
// Helper function to strip all image_url parts but keep text parts (including VFS paths)
const stripImageUrls = (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)) {
// Keep only text parts (this includes "Added file: /tmp/..." paths)
const textParts = msg.content.filter(part => part.type === 'text');
// If we had images, convert to string content (or empty if no text)
if (textParts.length > 0) {
return {
...msg,
content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n')
};
}
// If no text parts, return empty string
return {
...msg,
content: ''
};
}
return msg;
});
};
// Prepare messages for AI
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: 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);
// If this session has already determined images aren't supported, strip them proactively
if (session.imagesNotSupported) {
messages = stripImageUrls(messages);
}
// Prepare completion options
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
@@ -290,11 +358,56 @@ export class SessionManager {
},
};
// Generate streaming response
const stream = await openai.chat.completions.create(completionOptions, {
signal: session.abortController?.signal
// Check if messages contain any images (for retry logic)
const hasImages = messages.some(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
return msg.content.some(part => part.type === 'image_url');
}
return false;
});
// Generate streaming response with retry logic for models that don't support images
let stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;
let retriedWithoutImages = false;
try {
stream = await openai.chat.completions.create(completionOptions, {
signal: session.abortController?.signal
});
} catch (error) {
// Check if this might be an image-related error and we have images to strip
const errorObj = error as Record<string, unknown>;
const errorStatus = typeof errorObj?.status === 'number' ? errorObj.status : undefined;
const isPotentialImageError = errorStatus === 400 || errorStatus === 404 || errorStatus === 500;
if (isPotentialImageError && hasImages && !retriedWithoutImages) {
console.warn('API call failed, retrying without image_url parts (keeping VFS paths):', error);
retriedWithoutImages = true;
// Strip image_url parts but keep text parts (including VFS paths)
const messagesWithoutImages = stripImageUrls(messages);
// Update completion options with stripped messages
const retryOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
...completionOptions,
messages: messagesWithoutImages
};
// Retry the API call - if this succeeds, we know images were the problem
stream = await openai.chat.completions.create(retryOptions, {
signal: session.abortController?.signal
});
// SUCCESS: The retry without images worked, so this model doesn't support images
// Mark this session as not supporting images to avoid future retries
session.imagesNotSupported = true;
console.log('Retry without images succeeded - marking this session as not supporting images');
} else {
// Re-throw if not a potential image error or already retried
throw error;
}
}
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
@@ -609,7 +722,8 @@ export class SessionManager {
try {
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
await dotAI.setHistory(session.sessionName, session.messages);
// Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid
await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]);
} catch (error) {
console.warn('Failed to save session history:', error);
}
+115
View File
@@ -0,0 +1,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
* - 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
* @returns Promise resolving to message content (string or array of content parts)
*/
export async function buildMessageContent(
input: string,
attachedFiles: File[],
fs: JSRuntimeFS,
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({
type: 'text',
text: `Added file: ${result.vfsPath}`
});
}
} else {
contentParts.push(part);
}
}
}
// 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);
// 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 with base64 encoding
const isImage = file.type.startsWith('image/');
if (isImage) {
try {
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,
image_url: { url: imageUrl }
}];
} catch (error) {
// If URL conversion fails, just use text part
console.warn('Failed to convert image to base64, using text part only:', error);
}
}
return [textPart];
} catch (error) {
console.error('Failed to save file:', error);
return [{
type: 'text' as const,
text: `Failed to save file: ${file.name}`
}];
}
});
const fileResults = await Promise.all(filePromises);
// 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
if (contentParts.length === 1 && contentParts[0].type === 'text') {
return contentParts[0].text;
}
// Return array for multiple parts or if contains image URLs
return contentParts;
}
+23
View File
@@ -67,4 +67,27 @@ export async function saveFileToTmp(fs: JSRuntimeFS, file: File, tmpPath = '/tmp
await fs.writeFile(fullPath, uint8Array);
return fullPath;
}
/**
* Check if a file path represents a media/binary file that cannot be edited as text
* @param path - File path to check
* @returns boolean - True if the file is a media/binary file
*/
export function isMediaFile(path: string): boolean {
const extension = path.split('.').pop()?.toLowerCase();
if (!extension) return false;
const mediaExtensions = [
// Images
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'heic', 'heif',
// Videos
'mp4', 'webm', 'avi', 'mov', 'mkv', 'flv', 'wmv', 'm4v',
// Audio
'mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac', 'wma',
// Other binary formats
'pdf', 'zip', 'tar', 'gz', 'rar', '7z',
];
return mediaExtensions.includes(extension);
}
+124
View File
@@ -0,0 +1,124 @@
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { generateUniqueFilename } from './fileUtils';
/**
* Converts a File to a base64-encoded data URL for API consumption.
*
* @param file - The file to convert
* @returns Promise resolving to base64 data URL string
*/
export async function fileToUrl(file: File): Promise<string> {
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;
}
}
+79
View File
@@ -0,0 +1,79 @@
import type OpenAI from 'openai';
/**
* Detects image URLs in text and splits the text into content parts.
* Image URLs are identified by common image file extensions or data URLs.
*
* @param text - The input text that may contain image URLs
* @returns Array of content parts (text and image_url types)
*/
export function parseImageUrls(
text: string
): Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage> {
const trimmedText = text.trim();
// Return empty array if input is empty
if (!trimmedText) {
return [];
}
// Regex to match URLs (http/https) that end with image extensions or are data URLs
// Matches:
// - http:// or https:// URLs ending with image extensions (jpg, jpeg, png, gif, webp, svg, bmp, ico)
// - URLs with optional query parameters
// - Data URLs (data:image/...;base64,...)
const imageUrlRegex = /(https?:\/\/[^\s<>"']+\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?[^\s<>"']*)?|data:image\/[^;]+;base64,[^\s<>"']+)/gi;
const parts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage> = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
// Reset regex lastIndex
imageUrlRegex.lastIndex = 0;
while ((match = imageUrlRegex.exec(trimmedText)) !== null) {
// Add text before the URL
if (match.index > lastIndex) {
const textBefore = trimmedText.substring(lastIndex, match.index).trim();
if (textBefore) {
parts.push({
type: 'text',
text: textBefore
});
}
}
// Add the image URL
const imageUrl = match[0];
parts.push({
type: 'image_url',
image_url: {
url: imageUrl
}
});
lastIndex = match.index + match[0].length;
}
// Add remaining text after the last URL
if (lastIndex < trimmedText.length) {
const textAfter = trimmedText.substring(lastIndex).trim();
if (textAfter) {
parts.push({
type: 'text',
text: textAfter
});
}
}
// If no URLs were found, return the original text as a single text part
if (parts.length === 0) {
return [{
type: 'text',
text: trimmedText
}];
}
return parts;
}
+10 -37
View File
@@ -15,8 +15,7 @@ import { GiftCardRedeemDialog } from '@/components/GiftCardRedeemDialog';
import { Quilly } from '@/components/Quilly';
import { DotAI } from '@/lib/DotAI';
import type { AIMessage } from '@/lib/SessionManager';
import { saveFileToTmp } from '@/lib/fileUtils';
import type OpenAI from 'openai';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ModelSelector } from '@/components/ModelSelector';
@@ -245,48 +244,22 @@ export default function Index() {
}
);
// Build message content as text parts (same as ChatPane)
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
// Add user input as text part if present
if (prompt.trim()) {
contentParts.push({
type: 'text',
text: prompt.trim()
});
}
// Process attached files and add as separate text parts
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file);
return `Added file: ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `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
});
});
}
// Build message content from input and attached files
// Images are converted to base64-encoded data URLs
const messageContent = await buildMessageContent(
prompt.trim(),
attachedFiles,
fs,
undefined
);
// Store the initial message in chat history using DotAI
const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`);
const sessionName = DotAI.generateSessionName();
// Create initial message with content parts (same format as ChatPane)
const initialMessage: AIMessage = {
role: 'user',
content: contentParts.length === 1 ? contentParts[0].text : contentParts
content: messageContent
};
await dotAI.setHistory(sessionName, [initialMessage]);