Support adding files through the VFS

This commit is contained in:
Alex Gleason committed 2025-09-14 12:50:28 -05:00
1 parent be8309b503
commit a106a6e10b
6 files changed
+478 -6

No files matched your search

+4 -2
View File
@@ -5,6 +5,7 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Attach files directly to chat messages for AI processing
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
@@ -15,8 +16,9 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Edit Code**: Switch to the code view to manually edit files if needed
4. **Preview**: View your website in the preview pane
3. **Attach Files**: Click the paperclip icon to attach files to your messages for AI analysis
4. **Edit Code**: Switch to the code view to manually edit files if needed
5. **Preview**: View your website in the preview pane
## Project Structure
+48 -4
View File
@@ -5,6 +5,7 @@ import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
@@ -36,6 +37,7 @@ import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { makeSystemPrompt } from '@/lib/system';
import { assistantContentEmpty } from '@/lib/ai-messages';
import { saveFileToTmp } from '@/lib/fileUtils';
interface ChatPaneProps {
projectId: string;
@@ -67,6 +69,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [input, setInput] = useState('');
const [systemPrompt, setSystemPrompt] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -274,12 +277,44 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [messages, streamingMessage, isLoading]);
const handleSend = async () => {
if (!input.trim() || isLoading || !providerModel.trim()) return;
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
const messageContent = input;
const handleFileRemove = (fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
const handleSend = async () => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
let messageContent = input;
const modelToUse = providerModel.trim();
// Process attached files
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
const savedPath = await saveFileToTmp(fs, file);
return `File added to ${savedPath}`;
} catch (error) {
console.error('Failed to save file:', error);
return `Failed to save file: ${file.name}`;
}
});
const fileResults = await Promise.all(filePromises);
// Append file information to the message
if (messageContent.trim()) {
messageContent += '\n\n' + fileResults.join('\n');
} else {
messageContent = fileResults.join('\n');
}
}
setInput('');
setAttachedFiles([]);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
@@ -464,6 +499,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
{/* Bottom Controls Row */}
<div className="absolute bottom-2 left-2 right-2 flex items-center gap-4">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
@@ -526,7 +570,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={!input.trim() || !providerModel.trim()}
disabled={(!input.trim() && attachedFiles.length === 0) || !providerModel.trim()}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
+102
View File
@@ -0,0 +1,102 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { FileAttachment } from './file-attachment';
describe('FileAttachment', () => {
it('renders the attachment button', () => {
const onFileSelect = vi.fn();
render(
<FileAttachment onFileSelect={onFileSelect} />
);
const button = screen.getByRole('button');
expect(button).toBeInTheDocument();
});
it('calls onFileSelect when file is selected', async () => {
const onFileSelect = vi.fn();
render(
<FileAttachment onFileSelect={onFileSelect} />
);
const button = screen.getByRole('button');
fireEvent.click(button);
// Get the hidden file input
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput).toBeInTheDocument();
// Create a mock file
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
// Mock the file input change event
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(onFileSelect).toHaveBeenCalledWith(file);
});
it('displays selected files', () => {
const onFileSelect = vi.fn();
const onFileRemove = vi.fn();
const selectedFiles = [
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
];
render(
<FileAttachment
onFileSelect={onFileSelect}
onFileRemove={onFileRemove}
selectedFiles={selectedFiles}
/>
);
expect(screen.getByText('file1.txt')).toBeInTheDocument();
expect(screen.getByText('file2.txt')).toBeInTheDocument();
});
it('calls onFileRemove when remove button is clicked', () => {
const onFileSelect = vi.fn();
const onFileRemove = vi.fn();
const selectedFiles = [
new File(['content'], 'test.txt', { type: 'text/plain' }),
];
render(
<FileAttachment
onFileSelect={onFileSelect}
onFileRemove={onFileRemove}
selectedFiles={selectedFiles}
/>
);
const removeButtons = screen.getAllByRole('button');
// First button is the attachment button, second is the remove button
const removeButton = removeButtons[1];
fireEvent.click(removeButton);
expect(onFileRemove).toHaveBeenCalledWith(selectedFiles[0]);
});
it('disables interaction when disabled prop is true', () => {
const onFileSelect = vi.fn();
render(
<FileAttachment onFileSelect={onFileSelect} disabled={true} />
);
const button = screen.getByRole('button');
expect(button).toBeDisabled();
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput).toBeDisabled();
});
});
+100
View File
@@ -0,0 +1,100 @@
import React, { useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Paperclip, X } from 'lucide-react';
import { cn } from '@/lib/utils';
interface FileAttachmentProps {
onFileSelect: (file: File) => void;
onFileRemove?: (file: File) => void;
selectedFiles?: File[];
disabled?: boolean;
accept?: string;
multiple?: boolean;
className?: string;
}
export function FileAttachment({
onFileSelect,
onFileRemove,
selectedFiles = [],
disabled = false,
accept,
multiple = false,
className
}: FileAttachmentProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleButtonClick = () => {
fileInputRef.current?.click();
};
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if (files) {
Array.from(files).forEach(file => {
onFileSelect(file);
});
}
// Reset input so the same file can be selected again
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const handleRemoveFile = (file: File) => {
if (onFileRemove) {
onFileRemove(file);
}
};
return (
<div className={cn("flex items-center gap-2", className)}>
<input
ref={fileInputRef}
type="file"
onChange={handleFileChange}
accept={accept}
multiple={multiple}
className="hidden"
disabled={disabled}
/>
<Button
type="button"
variant="ghost"
size="sm"
onClick={handleButtonClick}
disabled={disabled}
className="h-8 w-8 p-0 hover:bg-muted/50"
>
<Paperclip className="h-4 w-4" />
</Button>
{selectedFiles.length > 0 && (
<div className="flex flex-wrap gap-1 max-w-48">
{selectedFiles.map((file, index) => (
<div
key={`${file.name}-${index}`}
className="flex items-center gap-1 px-2 py-1 bg-muted/50 rounded-md text-xs"
>
<span className="truncate max-w-24" title={file.name}>
{file.name}
</span>
{onFileRemove && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => handleRemoveFile(file)}
className="h-3 w-3 p-0 hover:bg-muted/70"
>
<X className="h-2 w-2" />
</Button>
)}
</div>
))}
</div>
)}
</div>
);
}
+157
View File
@@ -0,0 +1,157 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { generateUniqueFilename, saveFileToTmp } from './fileUtils';
import type { JSRuntimeFS } from './JSRuntime';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files = new Map<string, Uint8Array | string>();
private directories = new Set<string>();
constructor() {
this.directories.add('/');
this.directories.add('/tmp');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const data = this.files.get(path);
if (!data) throw new Error(`File not found: ${path}`);
if (encoding === 'utf8') {
return typeof data === 'string' ? data : new TextDecoder().decode(data);
}
return data;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
this.files.set(path, data);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]> {
if (_options?.withFileTypes) {
return [];
}
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.directories.add(path);
}
async stat(path: string) {
if (this.files.has(path)) {
return {
isDirectory: () => false,
isFile: () => true,
size: 100,
mtimeMs: Date.now()
};
}
if (this.directories.has(path)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
throw new Error(`File not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(): Promise<void> {}
async rmdir(): Promise<void> {}
async rename(): Promise<void> {}
async readlink(): Promise<string> { return ''; }
async symlink(): Promise<void> {}
}
describe('fileUtils', () => {
let mockFS: MockFS;
beforeEach(() => {
mockFS = new MockFS();
});
describe('generateUniqueFilename', () => {
it('should return original filename if no conflict', async () => {
const result = await generateUniqueFilename(mockFS, '/tmp', 'test.txt');
expect(result).toBe('test.txt');
});
it('should add counter for conflicting filenames', async () => {
// Simulate existing files
await mockFS.writeFile('/tmp/test.txt', 'content');
await mockFS.writeFile('/tmp/test_1.txt', 'content');
const result = await generateUniqueFilename(mockFS, '/tmp', 'test.txt');
expect(result).toBe('test_2.txt');
});
it('should handle files without extension', async () => {
await mockFS.writeFile('/tmp/README', 'content');
const result = await generateUniqueFilename(mockFS, '/tmp', 'README');
expect(result).toBe('README_1');
});
it('should handle multiple extensions correctly', async () => {
await mockFS.writeFile('/tmp/archive.tar.gz', 'content');
const result = await generateUniqueFilename(mockFS, '/tmp', 'archive.tar.gz');
expect(result).toBe('archive.tar_1.gz');
});
});
describe('saveFileToTmp', () => {
it('should save file to /tmp directory', async () => {
const fileContent = 'Hello, world!';
const arrayBuffer = new TextEncoder().encode(fileContent).buffer;
// Create a mock File object with arrayBuffer method
const file = {
name: 'hello.txt',
arrayBuffer: async () => arrayBuffer
} as File;
const savedPath = await saveFileToTmp(mockFS, file);
expect(savedPath).toBe('/tmp/hello.txt');
// Verify file was actually saved
const savedContent = await mockFS.readFile('/tmp/hello.txt', 'utf8');
expect(savedContent).toBe(fileContent);
});
it('should handle file deduplication', async () => {
// Create existing file
await mockFS.writeFile('/tmp/test.txt', 'existing');
const fileContent = 'new content';
const arrayBuffer = new TextEncoder().encode(fileContent).buffer;
// Create a mock File object with arrayBuffer method
const file = {
name: 'test.txt',
arrayBuffer: async () => arrayBuffer
} as File;
const savedPath = await saveFileToTmp(mockFS, file);
expect(savedPath).toBe('/tmp/test_1.txt');
// Verify new file was saved with unique name
const savedContent = await mockFS.readFile('/tmp/test_1.txt', 'utf8');
expect(savedContent).toBe(fileContent);
});
});
});
+67
View File
@@ -0,0 +1,67 @@
import type { JSRuntimeFS } from '@/lib/JSRuntime';
/**
* Generate a unique filename by adding numbers if the file already exists
* @param fs - Filesystem instance
* @param directory - Directory to check for existing files
* @param filename - Original filename
* @returns Promise<string> - Unique filename
*/
export async function generateUniqueFilename(
fs: JSRuntimeFS,
directory: string,
filename: string
): Promise<string> {
// Ensure directory exists
try {
await fs.mkdir(directory, { recursive: true });
} catch {
// Directory might already exist, continue
}
// Parse filename and extension
const lastDotIndex = filename.lastIndexOf('.');
const name = lastDotIndex === -1 ? filename : filename.slice(0, lastDotIndex);
const extension = lastDotIndex === -1 ? '' : filename.slice(lastDotIndex);
let uniqueFilename = filename;
let counter = 1;
// Keep checking for existing files and increment counter
while (true) {
const fullPath = `${directory}/${uniqueFilename}`;
try {
await fs.stat(fullPath);
// File exists, try next number
uniqueFilename = `${name}_${counter}${extension}`;
counter++;
} catch {
// File doesn't exist, we can use this filename
break;
}
}
return uniqueFilename;
}
/**
* Save a file to the /tmp directory with deduplication
* @param fs - Filesystem instance
* @param file - File object to save
* @returns Promise<string> - Full path where the file was saved
*/
export async function saveFileToTmp(fs: JSRuntimeFS, file: File): Promise<string> {
const tmpDir = '/tmp';
const uniqueFilename = await generateUniqueFilename(fs, tmpDir, file.name);
const fullPath = `${tmpDir}/${uniqueFilename}`;
// Read file content as array buffer and convert to Uint8Array
const arrayBuffer = await file.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
// Write file to filesystem
await fs.writeFile(fullPath, uint8Array);
return fullPath;
}